Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and C++11 class static member, double should use "constexpr" while int can be "const", why?

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

like image 837
Hind Forsum Avatar asked Mar 09 '17 03:03

Hind Forsum


1 Answers

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.

like image 140
AnT Avatar answered Sep 28 '22 15:09

AnT