我目前正在研究更多 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 表示函数调用必须在常量表达式中具有常量值
。
当我按以下方式声明 PI
时,它会起作用:
static const double PI = atan(1) * 4;
编译器在这里似乎不喜欢 constexpr
而喜欢 static const
的实际原因是什么? constexpr
不应该在这里也符合条件吗?还是这里的一切都与上下文有关,并且 constexpr
不应该在函数之外声明?
谢谢。
最佳答案
What is the actual reason the compiler doesn't seem to like
constexpr
butstatic const
here?
constexpr
必须在编译时可计算,而 static const
则不需要。
static const double PI = atan(1) * 4;
只是告诉编译器PI
一旦初始化就不能修改,但可以在运行时初始化。
关于c++ - 在命名空间中使用 constexpr double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43352827/