c++ - const 变量的值在常量表达式中是否可用,取决于变量类型

标签 c++ c++11 constants constexpr

下面的代码没问题:

constexpr double square_cstxpr(double x) { return x * x; }

int main() {
    const int test = 5;
    constexpr double result = square_cstxpr((double)test);
}

但是,如果将 test 的类型从 const int 更改为 const double,g++ 会给出以下错误:the 'test' 的值在常量表达式中不可用

在此处查看 g++ 的代码和输出:http://coliru.stacked-crooked.com/a/2fe9b176c2b23798

有人能解释一下这种行为吗?

最佳答案

constexprconst 变量必须是整数或枚举类型才能在常量表达式中使用。见 [expr.const]/2 :

an lvalue-to-rvalue conversion unless it is applied to

(2.7.1) a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or [..]

造成这种限制的原因主要是历史原因。当涉及到常量表达式时, float 已经被小心处理了;考虑非类型模板参数。这是由于它们强烈依赖于平台的行为导致编译时计算的数学化程度低于应有的程度。

关于c++ - const 变量的值在常量表达式中是否可用,取决于变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45593044/

相关文章:

c++ - 指针和引用作为 const 对象的成员变量

c++ - 函数参数中的 const'ing 原始类型是否会显着提高性能?

reactjs - 在 react 类(和 meteor )中使用 'const'

c++ - boost::asio 在 ssl 连接后发送获取请求

C++返回 vector ,无法弄清楚出了什么问题

c++ - 我怎样才能用这段代码把 cin 变成小写?

C++11 - 计算数字 vector 中的模式时出错

c++ - Clang-Tidy : Move constructor initializes class member by calling a copy constructor

c++ - Linux下的服务,一种现代方法?

c++ - 模板类的模板函数特化