gpt4 book ai didi

c++ - g++ 在 static_assert 中接受 const 作为 constexpr

转载 作者:太空狗 更新时间:2023-10-29 21:39:43 25 4
gpt4 key购买 nike

当使用 g++ 4.8.2-std=c++11 标志编译以下代码时,编译没有错误:

    constexpr double C = 299792.458;
const double local_max = 3.5;
static_assert(local_max < C, "can't go that fast");

编译以下代码时出现错误:

    constexpr double C = 299792.458;
double x = 3.5;
const double local_max = x;
static_assert(local_max < C, "can't go that fast");

错误信息:

a.cc: In function ‘int main()’:

a.cc:6:2: error: non-constant condition for static assertion
static_assert(local_max < C, "can't go that fast");

a.cc:6:2: error: the value of ‘local_max’ is not usable in a constant expression

a.cc:5:15: note: ‘local_max’ was not declared ‘constexpr’ const double local_max = x;

我的问题是为什么它在第一种情况下不报错。

这是否取决于 const 变量是否使用 constexpr 初始化?

最佳答案

你是完全正确的,之后

const double local_max = 3.5;

local_max 仍然不应该是编译时常量。这是一个编译器错误,已在 GCC 5.1 中修复。您可以在 gcc.godbolt.org 上验证这一点,您将在其中看到 GCC 的错误消息,包括:

error: the value of 'local_max' is not usable in a constant expression

note: 'local_max' was not declared 'constexpr'

关于c++ - g++ 在 static_assert 中接受 const 作为 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226221/

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