Home >Backend Development >C++ >How Can I Initialize a Static constexpr Member Using a Static constexpr Function in C ?

How Can I Initialize a Static constexpr Member Using a Static constexpr Function in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 07:02:171053browse

How Can I Initialize a Static constexpr Member Using a Static constexpr Function in C  ?

constexpr Initializing Static Member Using Static Function

Issue

The goal is to obtain a compile-time constant (constexpr value) calculated from a constexpr function, both within the same class namespace.

First Attempt

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.

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));

While this compiles on g -4.5.3, g -4.6.3 shows inconsistency and redeclaration errors.

Explanation

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.

Conclusion

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!

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