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