下面的代码没问题:
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
有人能解释一下这种行为吗?
最佳答案
非constexpr
但const
变量必须是整数或枚举类型才能在常量表达式中使用。见 [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/