用const, - int vs float初始化一个constexpr
问题描述:
我想知道为什么整数 ii
在编译时初始化,而不是float ff
这里:
I'm wondering why the integer ii
is initiallized at compile time, but not the float ff
here:
int main() {
const int i = 1;
constexpr int ii = i;
const float f = 1.0;
constexpr float ff = f;
}
这是当我尝试编译时会发生什么:
This is what happens when I try to compile:
> g++ -std=c++11 test.cc
test.cc: In function ‘int main()’:
test.cc:6:24: error: the value of ‘f’ is not usable in a constant expression
constexpr float ff = f;
^
test.cc:5:15: note: ‘f’ was not declared ‘constexpr’
const float f = 1.0;
答
>积分常数表达式(事实上暗示 constexpr
;请参见ISO C ++中的expr.const)。 float
不是一个整数类型,并且不满足常量表达式的要求,而不使用 constexpr
。 (类似的情况是为什么 int
可以但 float
不能是模板参数。)
Constant variables of integral types with constant initializers are integral constant expressions (de facto implicitely constexpr
; see expr.const in ISO C++). float
is not an integral type and does not meet the requirements for constant expression without the use of constexpr
. (A similar case is why int
can be but float
cannot be a template parameter.)