【问题标题】:g++ accepts const as constexpr in static_assertg++ 在 static_assert 中接受 const 作为 constexpr
【发布时间】:2015-08-26 12:08:11
【问题描述】:

当使用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:在函数“int main()”中:

a.cc:6:2: 错误:静态断言的非常量条件
static_assert(local_max

a.cc:6:2: 错误:‘local_max’的值不能用于常量 表达

a.cc:5:15: 注意:'local_max' 没有被声明为 'constexpr' const 双local_max = x;

我的问题是为什么它在第一种情况下没有给出错误。

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

【问题讨论】:

  • x 在运行时获取它的值,而 static_assert 是编译时断言。您不能基于 x 制作 static_assert。

标签: c++ c++11


【解决方案1】:

你是完全正确的,之后

const double local_max = 3.5;

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

错误:'local_max' 的值在常量表达式中不可用

注意:“local_max”未声明为“constexpr”

【讨论】:

  • 为什么不能是编译时间常数?那为什么const int i = 0; int x[i]会编译呢?
  • @0x499602D2 整数类型的规则很特殊。 OP 猜测的内容(如果使用常量表达式初始化,则有效隐含 constexpr)确实适用于整数类型,以便让大多数有效的 C++03 代码也成为有效的 C++11 代码。
【解决方案2】:

第一个版本正在运行,因为 local_max 不会在内存中。每当您使用 local_max 时,它将被替换为它的值,该值在编译时是已知的。所以你可以基于它调用一个static_assert。

然而,在第二个版本中,local_max 根据 x 获取它的值,它是在运行时获取它的值。

您不能基于在运行时获取其值的变量来创建 static_assert,因为 static_assert 是编译时断言。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-13
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多