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

Can a Static Constexpr Member Be Initialized Using a Constexpr Function in C ?

Barbara Streisand
Release: 2024-12-04 06:50:20
Original
1062 people have browsed it

Can a Static Constexpr Member Be Initialized Using a Constexpr Function in C  ?

Constexpr Initializing Static Member Using Static Function

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template