在命名空间中使用 constexpr double

using constexpr double in namespaces

本文关键字:constexpr double 命名空间      更新时间:2023-10-16

我目前正在研究更多 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
}

。但在这里智能感知说function call must have a constant value in a constant expression.

当我以下列方式声明PI时,它可以工作:

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

编译器似乎不喜欢constexprstatic const在这里的真正原因是什么?constexpr不应该在这里也有资格,还是这里的上下文和constexpr不应该在函数之外声明?

谢谢。

编译器

似乎不喜欢constexpr但在这里static const的真正原因是什么?

constexpr必须在编译时可计算,而static const则不需要。

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

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