The Foo1
case is indeed non-conforming and if we build using -std=c++98 -pedantic
gcc will warn as follows (see it live):
error: floating-point literal cannot appear in a constant-expression
static const double A=2.5;
^
warning: ISO C++ forbids initialization of member constant 'Foo1::A' of non-integral type 'const double' [-Wpedantic]
While compiling without -pedantic
does not yield any error or warning (see it live)
So this must be an extension and if we use clang using -std=C++98 -pedantic
we see this message:
warning: in-class initializer for static data member of type 'const double' is a GNU extension [-Wgnu-static-float-init]
static const double A=2.5;
^ ~~~
which seems to confirm this is an extension.
This restriction on floating point was kept in C++11 to remain compatible with C++03 and to encourage consistent use of constexpr see: Constant expression initializer for static class member of type double.
This is also the case for Foo2
initializing C
is allowed as an extension, the result of the division will be int since the type of the result depends on the type of the operands and does not depend on what you assign it to.
Update
This is a depreciated extension:
G++ allows static data members of const floating-point type to be declared with an initializer in a class definition. The standard only allows initializers for static members of const integral types and const enumeration types so this extension has been deprecated and will be removed from a future version.
There is a more detailed gcc bug report that discusses the validity of the extension and other related issues around it.
It seemed odd that using -pedantic
was sufficient by itself to turn this into an error, there is a gcc bug report that covers that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…