在命名空间中使用 constexpr double
using constexpr double in namespaces
我目前正在研究更多 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;
编译器似乎不喜欢constexpr
但static const
在这里的真正原因是什么?constexpr
不应该在这里也有资格,还是这里的上下文和constexpr
不应该在函数之外声明?
谢谢。
编译器
似乎不喜欢
constexpr
但在这里static const
的真正原因是什么?
constexpr
必须在编译时可计算,而static const
则不需要。
static const double PI = atan(1) * 4;
只是告诉编译器,PI
初始化后不能修改,但可以在运行时初始化。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 多成员Constexpr结构初始化
- 条件constexpr函数
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- Visual C++ constexpr Hints
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 为什么constexpr的性能比正常表达式差
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 为什么std::isnan 不是 constexpr?
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 更多constexpr容器是否需要mark_immutable_if_consexpr
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- constexpr上下文中std::initializer_list的验证
- constexpr构造函数需要常量成员函数时出现问题
- C++在数学计算中将double转换为int
- Clang说is_same_v<int,double>的用法不是constexpr,不知道它怎么不是
- 在命名空间中使用 constexpr double
- 为什么 std::array::size constexpr 具有简单类型(int、double、..),而不是 std