Home >Backend Development >C++ >How Can I Initialize a Static constexpr Member Using a Static constexpr Function in C ?
The goal is to obtain a compile-time constant (constexpr value) calculated from a constexpr function, both within the same class namespace.
class C1 { constexpr static int foo(int x) { return x + 1; } constexpr static int bar = foo(sizeof(int)); };
However, this fails on both g -4.5.3 and g -4.6.3, citing the use of non-constant expressions in the initializer.
class C2 { constexpr static int foo(int x) { return x + 1; } constexpr static int bar; }; constexpr int C2::bar = C2::foo(sizeof(int));
While this compiles on g -4.5.3, g -4.6.3 shows inconsistency and redeclaration errors.
According to the C Standard (section 9.4.2), a constexpr static data member can only be declared with a brace-or-equal-initializer in the class definition, where every initializer-clause must be a constant expression.
In the "second attempt," the declaration lacks the required brace-or-equal-initializer.
Contrary to initial assumptions, both attempts prove unsuccessful. The Standard prohibits initializing static constexpr data members in contexts where the class is complete.
The above is the detailed content of How Can I Initialize a Static constexpr Member Using a Static constexpr Function in C ?. For more information, please follow other related articles on the PHP Chinese website!