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
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.
constexpr
is 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.