【发布时间】:2017-04-11 17:42:06
【问题描述】:
我目前正在研究更多 C++11 的内容,并且跳了大约 constexpr。在我的一本书中,有人说你应该将它用于像 π 这样的常量,例如:
#include <cmath>
// (...)
constexpr double PI = atan(1) * 4;
现在我想把它放在一个自己的命名空间中,例如。 MathC:
// config.h
#include <cmath>
namespace MathC {
constexpr double PI = atan(1) * 4;
// further declarations here
}
...但是这里的 IntelliSense 说 function call must have a constant value in a constant expression。
当我通过以下方式声明 PI 时,它会起作用:
static const double PI = atan(1) * 4;
编译器在这里似乎不喜欢constexpr 而喜欢static const 的实际原因是什么? constexpr 不应该在这里也符合条件,还是这里的上下文和 constexpr 不应该在函数之外声明?
谢谢。
【问题讨论】:
-
atan不是constexpr。见this question。 -
你在用什么书,这段代码在什么页/节。
-
看来这似乎是本书作者的错误。这是 Jürgen Wolf 的一本名为“C++ - Das umfassende Handbuch”的德国书,出版于 Rheinwerk Computing,2014 年第 2 版,第 250 页。上面清楚地写着
constexpr double PI_V3 = atan(1)*4;。 -
你能分享一下那是哪本书吗?
-
@ΦXocę웃Пepeúpaツ 当然,这是德国亚马逊链接:amazon.de/umfassende-Handbuch-aktuell-Standard-Computing/dp/…