Home >Backend Development >C++ >How Can a `constexpr` Static Member Be Initialized Using a `constexpr` Static Function in C ?

How Can a `constexpr` Static Member Be Initialized Using a `constexpr` Static Function in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 22:35:11884browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn