简体   繁体   English

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

[英]g++ accepts const as constexpr in static_assert

When compiling the following code with g++ 4.8.2 and -std=c++11 flag it compiles with no errors: 使用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");

When compiling the following code it gives error: 编译以下代码时会出错:

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

Error message: 错误信息:

a.cc: In function 'int main()': a.cc:在函数'int main()'中:

a.cc:6:2: error: non-constant condition for static assertion a.cc:6:2:错误:静态断言的非常数条件
static_assert(local_max < C, "can't go that fast"); static_assert(local_max <C,“不能那么快”);

a.cc:6:2: error: the value of 'local_max' is not usable in a constant expression a.cc:6:2:错误:'local_max'的值在常量表达式中不可用

a.cc:5:15: note: 'local_max' was not declared 'constexpr' const double local_max = x; a.cc:5:15:注意:'local_max'未声明为'constexpr'const double local_max = x;

My question is why it does not give error in the first case. 我的问题是为什么它在第一种情况下不会出错。

Does it depend on whether a const variable is initialized with a constexpr or not? 是否取决于是否使用constexpr初始化const变量?

You are entirely correct, after 之后你是完全正确的

const double local_max = 3.5;

local_max is still not supposed to be a compile-time constant. local_max仍然不应该是编译时常量。 This is a compiler bug, fixed in GCC 5.1. 这是一个编译器错误,已在GCC 5.1中修复。 You can verify this on gcc.godbolt.org , where you will see GCC's error messages, including: 您可以在gcc.godbolt.org上验证这一点 ,您将在其中看到GCC的错误消息,包括:

error: the value of 'local_max' is not usable in a constant expression 错误:'local_max'的值在常量表达式中不可用

and

note: 'local_max' was not declared 'constexpr' 注意:'local_max'未被声明为'constexpr'

The first version is working because the local_max won't be in the memory. 第一个版本正在运行,因为local_max不会在内存中。 Whenever you use local_max, it will be replaced with it's value, which is known at compile time. 无论何时使用local_max,它都将被替换为它的值,这在编译时是已知的。 So you can call a static_assert based on it. 所以你可以根据它调用static_assert。

However, in the second version local_max get it's value based on x, which is getting it's value at runtime. 但是,在第二个版本中,local_max基于x得到它的值,它在运行时得到它的值。

You can't make a static_assert based on a variable which is getting it's value at runtime, because static_assert is a compile time assert. 您不能基于在运行时获取它的值的变量来创建static_assert,因为static_assert是编译时断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM