8

A structure C defined several static const members like this:

Code is like below:

#include<stdio.h>
struct C{
    static int i;
    static const int j=1;
    static constexpr double d=1;
    static const double d1=1.0;
};
int main(){
    return 0;
}

Compilation will lead to error:

$g++ testStatic.cpp -std=c++11
testStatic.cpp:6:25: error: in-class initializer for static data member of
      type 'const double' requires 'constexpr' specifier
      [-Wstatic-float-init]
    static const double d1=1.0;
                        ^  ~~~
testStatic.cpp:6:5: note: add 'constexpr'
    static const double d1=1.0;
    ^
    constexpr
1 error generated.

Why so weird Why static int can be const,double should be constexpr,what's the rational

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119
  • Integral constant expressions have always been special in C++. Basically, they are the kinds of values you can reason about without having to consider platform-dependent details, and they're the kinds of values you can use as (non-type) template arguments. – Kerrek SB Mar 09 '17 at 03:40
  • Read [Constant expression initializer for static class member of type double](http://stackoverflow.com/a/30742473/1708801) you will find a lot of background there. See also [Why type const double is not captured by lambda from reaching-scope, but const int is?](http://stackoverflow.com/a/34362729/1708801) which is somewhat related. – Shafik Yaghmour Mar 09 '17 at 04:11

1 Answers1

6

const follows the original language specification defined in C++98 and C++03. It was generally disallowed to supply an in-class initalizers for static const members in C++98. The possibility to do so for static const objects of integral and enum types in C++98 was part of special treatment given to these types.

constexpris a new feature introduced in C++11. It is designed differently and works uniformly for all types.

So, you can just use constexpr for both integer and floating point types and forget about any non-uniformities.

If you continue to use const in such contexts, you will have to deal with C++98 legacy. However, C++17 will introduce inline variables, which should also make it possible to use in-class initializers for inline static const objects of any type.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765