The definition is different from the declaration for the static member constexpr

Consider the code

#include <iostream> struct Foo { constexpr static int n = 42; }; const int Foo::n; // note const, NOT constexpr int main() { std::cout << Foo::n; } 

The definition of a static member is different from the declaration inside the class, i.e. const used instead of constexpr . Is the code above legal, and if so, why? It compiles with both gcc and clang. It also compiles if we confused const and constexpr in the definition and declaration, respectively. I know that constexpr implies const for variables, but not vice versa.

+6
source share
1 answer

My two cents, looking at some kind of documentation like that one .

Actually, it can really be.

In fact, the difference between constexpr and const mainly depends on their goals, but the former implies that the latter is a side effect.

There is also a more subtle difference: constexpr is a specifier, and const is a type classifier.

In particular:

The main function of const is to express the idea that the object is not modified through the interface

On the other hand:

The main function of constexprs is to expand the range of values ​​that can be calculated at compile time, which makes this type of calculation safe and can also be used in compile-time contexts.

Or even more concise from here :

constexpr - indicates that the value of a variable or function can be displayed in constant expressions

In any case, it happens that:

constexpr before defining a variable [...] implies const

So, although the reason you should use constexpr instead of const is understandable, and everyone tends to remember that:

constexpr is not a general replacement for const (or vice versa)

It is a fact that with constexpr you are actually saying that this member is implicitly const (you also have a set of more specific restrictions on how this member can be defined).

In any case, after the definition, the member is nothing more than a data element that has a qualifier of type const (which can be used in constant expressions), this is what you declare outside your class.

+1
source

All Articles