加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么这不是constexpr?

发布时间:2020-12-16 04:58:32 所属栏目:百科 来源:网络整理
导读:#include iostreamunion gc_bits { size_t value; struct { size_t arena : 2; } bits; constexpr gc_bits(size_t value_) : value(value_) { }};static constexpr size_t get_max_arenas() { return gc_bits(~0ULL).bits.arena;}size_t current_colour[get_
#include <iostream>

union gc_bits {
    size_t value;
    struct {
        size_t arena : 2;
    } bits;

    constexpr gc_bits(size_t value_) : value(value_) {
    }
};

static constexpr size_t get_max_arenas() {
    return gc_bits(~0ULL).bits.arena;
}

size_t current_colour[get_max_arenas()]; // error

int main() {
    std::cout << get_max_arenas() << std::endl;
}

数组声明错误,因为get_max_arenas不是constexpr.我不清楚为什么会这样.

解决方法

稍微改写一下你的程序:
static constexpr auto gma = get_max_arenas();

size_t current_colour[gma]; // error

给出了Clang错误:

read of member ‘bits’ of union with active member ‘value’ is not
allowed in a constant expression

您收到此错误的原因是构造函数设置了值,然后您尝试读取位.正如@gurka所评论的那样,这是不允许的.

Standard报价:

[expr.const]

2 A conditional-expression e is a core constant expression unless the
evaluation of e,following the rules of the abstract machine (1.9),
would evaluate one of the following expressions:

(2.8) — an lvalue-to-rvalue conversion (4.1) or modification (5.18,
5.2.6,5.3.2) that is applied to a glvalue that refers to a non-active member of a union or a subobject thereof;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读