gpt4 book ai didi

c++ - 具有非固定类型的枚举的初始值设定项

转载 作者:行者123 更新时间:2023-11-28 06:30:57 25 4
gpt4 key购买 nike

标准在 7.2/5 [dcl.enum] 中说:

If the underlying type is not fixed, the type of each enumerator prior to the closing brace is determined as follows:

(5.1) — If an initializer is specified for an enumerator, the constant-expression shall be an integral constant expression (5.20). If the expression has unscoped enumeration type, the enumerator has the underlying type of that enumeration type, otherwise it has the same type as the expression.

(5.2) — If no initializer is specified for the first enumerator, its type is an unspecified signed integral type.

(5.3) — Otherwise the type of the enumerator is the same as that of the preceding enumerator unless the incremented value is not representable in that type, in which case the type is an unspecified integral type sufficient to contain the incremented value. If no such type exists, the program is ill-formed.

因此,5.15.2 涵盖了以下所有情况:

I. enum A { x = 4 };//案例 1,指定了初始化器

II. 枚举 B { x, y };//情况 2,未指定初始化器。

三.

enum C { x = 5 };

enum D { y = x }; // case 1, y had unscoped enumeration type.

四.

enum struct C { x = 5 };

enum D { y = 0, x = C::x }; // even integral constant expression must have integral
// or unscoped enumeration type, not 'C

DEMO

我想看看 5.3 的实际情况。为什么 case IV 连编译都没有?

最佳答案

将作用域枚举引入语言的全部意义在于防止隐式转换为基础类型。因此,在您失败的示例中,无法从 C::x 隐式转换为 D 的基础类型是什么整数类型。

添加适当的转换,您的代码即可编译。

#include <type_traits>

enum struct C { x = 5 };

enum D
{
y = 0,
x = static_cast<std::underlying_type<C>::type>(C::x)
};

Live demo

关于c++ - 具有非固定类型的枚举的初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27597163/

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