我想知道为什么整数ii在编译时初始化,但不是浮点数ff:
int main() {
const int i = 1;
constexpr int ii = i;
const float f = 1.0;
constexpr float ff = f;
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试编译时会发生的事情:
> 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;
Run Code Online (Sandbox Code Playgroud)
Ste*_*oft 16
具有常量初始值设定项的整数类型的常量变量是整型常量表达式(事实上是隐含的constexpr;请参阅ISO C++中的expr.const).float不是一个整数类型,不符合不使用的常量表达的要求constexpr.(类似的情况是为什么int可以但float不能是模板参数.)
bol*_*lov 10
在C++中,常量整数的处理方式与其他常量类型不同.如果使用编译时常量表达式初始化它们,则可以在编译时表达式中使用它们.这样做是为了使数组大小可以const int代替#defined(就像你在C中被强制一样):
(假设没有VLA扩展)
const int s = 10;
int a[s]; // OK in C++
Run Code Online (Sandbox Code Playgroud)