c++ - 在命名空间中使用 constexpr double

标签 c++ c++11 constexpr

我目前正在研究更多 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 but static const here?

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

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

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

关于c++ - 在命名空间中使用 constexpr double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43352827/

相关文章:

c++ - C++标准文档中的 "terms and definitions"如何解释?

c++ - 功能/不可变数据结构在非垃圾收集上下文中是否仍然对并发有用?

c++ - 如何使用 std::ref?

c++ - 如何在其值可用于常量表达式的类中初始化数组?

c++ - 为什么不能将constexpr函数传递给std::cout?

c++ - 有什么方法可以将右值/临时对象传递给需要非成本引用的函数?

c# - 在 C++/C# 之间的结构内传递字符串/数组

c++ - 无法在 gnu linux c++ 中写入 ostream 错误 : invalid operands of types ofstream and ‘const char [2]’ to binary ‘operator

c++ - 用不同的值初始化 const 容器的正确方法是什么?

c++ - 是否可以为 constexpr 函数定义类型别名