![](/img/trans.png)
[英]Killing Magic Numbers: "const int" vs "constexpr int" (or is there no difference in the end)
[英]Initializing a constexpr with a const, -- int vs float
我想知道为什么 integer ii
在编译时被初始化,而不是这里的 float ff
:
int main() {
const int i = 1;
constexpr int ii = i;
const float f = 1.0;
constexpr float ff = f;
}
这是我尝试编译时发生的情况:
> 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
不能是模板参数。)
在C ++中,常量整数的处理方式与其他常量类型不同。 如果使用编译时常量表达式初始化它们,则可以在编译时表达式中使用它们。 这样做是为了使数组大小可以是const int
而不是#define
d(就像你在C中被强制一样):
(假设没有VLA扩展)
const int s = 10;
int a[s]; // OK in C++
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.