c++11 - C++ Why can I initialize a static const char but not a static const double in a class definition? -


here 2 line of code:

static const double rydberg_const_ev = 13.6056953; static const char char_h_edge = '-'; 

the second line compiles without errors, first line not compile. (error: 'constexpr' needed in-class initialization of static data member...)

the solution apparently add keyword constexpr before type. required because double not "integral type". why behaviour differ between integer , floating point types?

i don't believe there reason except has grown historically.

the exception integral types desirable in pre-c++11 because people wanted use them array sizes. goes along other exception integral constants being treated constant expressions. exception doesn't exist floating-point types.

const int    ni = 10; const float  nf = 10.0f; int numbers1[(unsigned) ni];  // fine in versions of c++ int numbers2[(unsigned) nf];  // error in versions of c++ 

when c++11 introduced constexpr, special-casing const integral types , more. , works same way literal type. so, given superior tool, there no need dilate existing rules integral types floating-point.

today, special-casing of integral types left-over earlier darker days. cannot removed language because doing break existing code relies on special-casing there little gains complicating language further adding more exceptions entirely unneeded today constexpr. people should expected migrate constexpr , not worry old cruft more. believe reasonable decision argue decision should have been made.

addendum

as t.c. has commented, there has been (non)-defect report issue committee confirmed behavior won't changed , people supposed start using constexpr.

1826. const floating-point in constant expressions

section: 5.20 [expr.const] status: nad submitter: ville voutilainen date: 2014-01-04

a const integer initialized constant can used in constant expressions, const floating point variable initialized constant cannot. intentional, compatible c++03 while encouraging consistent use of constexpr. people have found distinction surprising, however.

it observed allowing const floating point variables constant expressions abi-breaking change, since affect lambda capture.

one possibility might deprecate use of const integral variables in constant expressions.

additional note, april, 2015:

ewg requested cwg allow use of const floating-point variables in constant expressions.

rationale (may, 2015):

cwg felt current rules should not changed , programmers desiring floating point values participate in constant expressions should use constexpr instead of const.


Comments