c++ - 将底层类型的任意值转换为强类型枚举类型是否安全?

标签 c++ enums c++11

如果我有一个强类型枚举,比如底层类型 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 classenum struct<声明的类型,标准将其分别称为 unscoped 枚举和 scoped 枚举。在 7.2 枚举声明 [dcl.enum] 中有更详细的描述。

枚举类型的不会与其枚举数混淆。在您的情况下,由于您声明的所有枚举都将 int 作为其基础类型,因此它们的值范围与 int 的值范围相同:来自 INT_MININT_MAX(含)。

由于 42 具有类型 int 并且显然是 int 的值,因此定义了行为。

关于c++ - 将底层类型的任意值转换为强类型枚举类型是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6974292/

相关文章:

java - 在另一个枚举的定义中迭代地使用一个枚举

c++ - 初始化程序列表不适用于 Visual Studio 2012 中的 vector ?

c++ - 在模板类中初始化类型为 'T &' 的静态成员的正确方法是什么?

c++ - 堆栈或 BSS 或数据段上的数组最大大小

Python C Api 将 PyObject * 传输到 c 数组

c++ - 生成唯一编号

c# - MongoDB 中枚举的自定义序列化

java - 仅在 for 循环中打印所有其他枚举值

c++ - unique_ptr 是否保证在 move 后存储 nullptr?

c++ - 书籍示例在类声明中使用 "explicit"关键字。无效吗?