c++ - 为什么每个常量表达式都可以转换为枚举类型

标签 c++ enums implicit-conversion

当我们定义枚举(范围内或非范围内)时,任何枚举器都具有其枚举的类型。例如,请考虑以下内容:

enum E { z=5 } //This unscoped enumerator has underlying type int implcitly

所以 const int 可以转换为 E。有标准转换吗?

最佳答案

Is there a standard conversion?

该标准在 §4.5/3 中规定:

A prvalue of an unscoped enumeration type whose underlying type is not fixed (7.2) can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range bmin to bmax as described in 7.2): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int. If none of the types in that list can represent all the values of the enumeration, a prvalue of an unscoped enumeration type can be converted to a prvalue of the extended integer type with lowest integer conversion rank (4.13) greater than the rank of long long in which all the values of the enumeration can be represented. If there are two such extended types, the signed one is chosen.

(强调我的)

第 §7.2/10 节还指定枚举器类型可以通过整数提升转换为整数,但反之则不行:

enum color { red, yellow, green=20, blue };
color c = 1; // error: type mismatch
int i = yellow; // OK: yellow converted to integral value 1

(来自标准的例子)

注意:所有引号均来自 N3936 draft .

关于c++ - 为什么每个常量表达式都可以转换为枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724244/

相关文章:

c# - 枚举设置为字符串并在需要时获取字符串值

c++ - 重载引用转换

c++ - 使用 QFileSystemModel 访问文件路径

c++ (double)0.700 * int(1000) => 699(不是 double 问题)

c# - c++ - 使用 std 命名空间和依赖项

python - 在 python 3 中遍历枚举时,并非所有元素都出现

c++ - 使用 boost transform_iterator 有条件地进行 std::transform

scala - 声明返回枚举的泛型方法

Scala 从 Try 到 Future 的隐式转换

c++ - 我如何处理这种情况 C++ sizeof 问题