"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can a Static Constexpr Member Be Initialized Using a Constexpr Function in C++?

Can a Static Constexpr Member Be Initialized Using a Constexpr Function in C++?

Published on 2024-12-22
Browse:916

Can a Static Constexpr Member Be Initialized Using a Constexpr Function in C  ?

Constexpr Initializing Static Member Using Static Function

Original Question:

In C , is it possible to compute a constexpr value (compile-time constant) from a constexpr function and store it as a static member of a class?

First Attempts and Compilers' Response:

The first attempt to define a static constexpr function foo within the class and initialize a static constexpr member bar using foo failed with errors in both g -4.5.3 and g -4.6.3.

Explanation:

As per the C Standard, a static constexpr data member can be initialized in the class definition using a brace-or-equal-initializer, where each initializer clause must be a constant expression. The provided code violated this rule, as the initialization of bar relied on the const expression foo(sizeof(int)) within the class body, making it not a constant expression.

Further Analysis:

Further attempts, including moving the constexpr function definition outside the class body, still resulted in errors in g -4.6.3, highlighting compiler-specific limitations.

Conclusion:

According to the C Standard, initializing a static constexpr data member with an initializer involving a constexpr function call is not allowed outside the definition of a constexpr function or constexpr constructor. This is due to the requirement that constexpr variables must be available as compile-time constants within member function bodies.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3