gpt4 book ai didi

c++ - 为什么这不是一个 constexpr?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:53 26 4
gpt4 key购买 nike

#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;

关于c++ - 为什么这不是一个 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32623906/

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