枚举 class 变量可以取整个范围的整数值吗?

Can an enum class variable take the full range of integer values?

有时您想要为某些整数值命名,但允许命名的值以外的其他值。在 C++ 中,这很容易用普通的 enum:

实现
enum { red, green, blue };
int color = 999;

假设在一些不寻常的上下文中,您想使用 enum class 进行类型检查,但也允许其他值:

enum class color_t { red, green, blue };
color_t color = (color_t)999;

这样还可以吗?或者是这样的情况,例如,编译器可以选择将 color_t 基于 char 而不是 int,这会使 999 不是基本类型的有效值?如果是后者,用enum class color_t: int?

显式声明基类型是否可以解决这个问题

枚举 类 默认情况下会是 int,如果你想要 char 你可以这样做:

enum class color_t : char { red, green, blue };

[dcl.enum]

8 For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type.

一旦基础类型固定,其范围内的任何值都是枚举值。枚举数只是该范围内的命名常量。

确定何时基础类型是固定的涉及一些细节,但它不适用于此处。作用域枚举始终具有固定类型(int 如果 none 已明确给出)。