Home >Backend Development >C++ >How Can a `constexpr` Static Member Be Initialized Using a `constexpr` Static Function in C ?
Using a constexpr Static Function to Initialize a constexpr Static Member
The goal of this code is to create a constexpr value in the namespace of a class by utilizing a constexpr static function and a static member. However, attempts to achieve this have encountered compilation errors with various versions of g .
First Attempt
class C1 { constexpr static int foo(int x) { return x + 1; } constexpr static int bar = foo(sizeof(int)); };
This code fails with g 4.5.3 and 4.6.3 due to the presence of a function call in the constexpr static member initialization.
Second Attempt
class C2 { constexpr static int foo(int x) { return x + 1; } constexpr static int bar; }; constexpr int C2::bar = C2::foo(sizeof(int));
This code fails with g 4.6.3 because the static constexpr data member must have an initializer in its declaration.
The Standard's Requirements
According to section 9.4.2 of the C Standard, a static data member of literal type can be declared in the class definition with the constexpr specifier. If so, the declaration must specify a brace-or-equal-initializer, where every initializer-clause is a constant expression.
In the "second attempt" code, the declaration does not have a brace-or-equal-initializer. Therefore, it does not meet the Standard's requirements.
Impossibility of the Goal
Unfortunately, the Standard precludes initializing a static constexpr data member in any context where the class is complete. This is because constexpr variables must be available as compile-time constant expressions from inside the bodies of member functions. Therefore, the variable initializers are completely defined before the function bodies, which means that the function is still incomplete in the context of the initializer. As a result, the expression is not considered a constant expression.
Conclusion
Due to limitations in the C Standard, it is not possible to initialize a static constexpr data member using a constexpr static function when the class is complete.
The above is the detailed content of How Can a `constexpr` Static Member Be Initialized Using a `constexpr` Static Function in C ?. For more information, please follow other related articles on the PHP Chinese website!