【问题标题】:using constexpr double in namespaces在命名空间中使用 constexpr double
【发布时间】: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/…

标签: c++ c++11 constexpr


【解决方案1】:

编译器在这里似乎不喜欢constexpr 而喜欢static const 的实际原因是什么?

constexpr 必须在编译时可评估,而 static const 不需要。

static const double PI = atan(1) * 4;

只是告诉编译器PI一旦初始化就不能修改,但可以在运行时初始化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多