gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:01 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com