In C++11 and C++14, why do I need constexpr
in the following snippet:
class Foo {
static constexpr double X = 0.75;
};
whereas this one produces a compiler error:
class Foo {
static const double X = 0.75;
};
and (more surprisingly) this compiles without errors?
class Foo {
static const double X;
};
const double Foo::X = 0.75;
In C++03 we were only allowed to provide an in class initializer for static member variables of const integral of enumeration types, in C++11 we could initialize a static member of literal type in class using constexpr. This restriction was kept in C++11 for const variables mainly for compatibility with C++03. We can see this from closed issue 1826: const floating-point in constant expressions which says:
CWG ended up closing this request as not a defect(NAD), basically saying:
For reference
N1804
the closest draft standard to C++03 publicly available in section9.4.2
[class.static.data] says:and the draft C++11 standard section
9.4.2
[class.static.data] says:this is pretty much the same in the draft C++14 standard.