如果我有一个强类型枚举,比如底层类型 int
,是否可以将不匹配任何枚举数的 int
值转换为枚举输入?
enum e1 : int { x = 0, y = 1 };
enum class e2 : int { x = 0, y = 1 };
int main() {
e1 foo = static_cast<e1>(42); // is this UB?
e2 bar = static_cast<e2>(42);
}
最佳答案
从 n3290,5.2.9 静态转换 [expr.static.cast]:
10 A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in that range). [...]
枚举类型包括那些用enum
声明的类型和那些用enum class
或enum struct<声明的类型
,标准将其分别称为 unscoped 枚举和 scoped 枚举。在 7.2 枚举声明 [dcl.enum] 中有更详细的描述。
枚举类型的值不会与其枚举数混淆。在您的情况下,由于您声明的所有枚举都将 int
作为其基础类型,因此它们的值范围与 int
的值范围相同:来自 INT_MIN
到 INT_MAX
(含)。
由于 42
具有类型 int
并且显然是 int
的值,因此定义了行为。
关于c++ - 将底层类型的任意值转换为强类型枚举类型是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6974292/