问题
Title says it all and both of the usual ways do not work. What am I missing?
1.
class Cl {
static constexpr double PI;
};
constexpr double Cl::PI = 3.14;
(26): error C2737: 'private: static double const Cl::PI' : 'constexpr' object must be initialized
2.
class Cl {
static constexpr double PI = 3.14;
};
(26): error C2864: 'Cl::PI' : a static data member with an in-class initializer must have non-volatile const integral type
type is 'const double'
In both attempts, the error is on the same line inside the class. I am using the VisualStudio/MSVC Nov 2013 CTP compiler.
Note that making the variable const
is not a solution because I want to use this constant in both constexpr functions and normal functions.
回答1:
By the tables and explanation from Stephan T. L. in this blog, the constexpr is indeed only partially implemented in VS Nov 2013 CTP.
The CTP supports C++11 constexpr, except for member functions. (Another limitation is that arrays aren't supported.) Also, it doesn't support C++14's extended constexpr rules.
(wish to put it in comments, but no sufficient points yet)
Edit: Just to add, in Herb's blog, there is near same question about static members, but the reply is the same as Stephan.
I think it is safe to simple say that Nov 2013 CTP not implement the required OP feature (send a bug report?) and wait for a Jul 2014 CTP or VS Next (sadly).
回答2:
You can't really "initialize" a constexpr. As the keyword implies, it's a constant expression, not a variable.
It seems you just want to use const
here.
The compiler in the second example just points out that you can't make all types const-expr.
Update: This appears to be a MSVC limitation.
- GCC http://coliru.stacked-crooked.com/a/009b60ebda296730 and
- Clang http://coliru.stacked-crooked.com/a/8b4e587450016441
are happy to oblige.
Indeed, the C++11 support page mentions: no constexpr
support in MSVC2010-2013
来源:https://stackoverflow.com/questions/23454507/initializing-a-static-constexpr-double-with-msvc-2013