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.
The above is the detailed content of Can a Static Constexpr Member Be Initialized Using a Constexpr Function in C ?. For more information, please follow other related articles on the PHP Chinese website!