【发布时间】:2017-04-29 17:34:11
【问题描述】:
以下代码编译失败live on Ideone:
#include <iostream>
using namespace std;
int main() {
const double kPi = 3.14;
constexpr double kPi2 = 2.0*kPi;
cout << kPi2;
}
错误信息是:
prog.cpp: In function 'int main()': prog.cpp:6:30: error: the value of 'kPi' is not usable in a constant expression constexpr double kPi2 = 2.0*kPi; ^ prog.cpp:5:15: note: 'kPi' was not declared 'constexpr' const double kPi = 3.14;
用constexpr、it compiles successfully 替换kPi 的const 声明。
另一方面,当使用int 代替double 时,看起来就像const plays well 和constexpr:
#include <iostream>
using namespace std;
int main() {
const int k1 = 10;
constexpr int k2 = 2*k1;
cout << k2 << '\n';
return 0;
}
为什么int 和double 在用const 初始化constexpr 时得到不同的处理?
这是 Ideone 编译器中的错误吗?这是 C++ 标准所要求的吗?这是为什么呢?
上面的代码是UB吗?
P.S.我尝试使用 Visual Studio 2015 C++ 编译器,它编译了第一个代码 sn-p(用 const 初始化 constexpr)就好了。
【问题讨论】:
-
issue 1826: const floating-point in constant expressions 涵盖了一些关于为什么浮点数被区别对待的历史。还有interesting deprecated gcc exntension.
-
@ShafikYaghmour 谢谢。我赞成那个帖子。
-
似乎应该将@ShafikYaghmour 的评论提升为答案然后接受。
-
如果@ShafikYaghmour 想写一个答案,我很乐意投票并接受它。
标签: c++ c++11 constants constexpr