将基础类型的任意值转换为强类型枚举类型是否安全?

发布于 2024-11-28 17:45:01 字数 301 浏览 1 评论 0原文

如果我有一个强类型枚举,例如基础类型 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);
}

If I have a strongly-typed enum, with say, underlying type int, is it ok to cast an int value that does not match any enumerator to the enum type?

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);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍风燃霜 2024-12-05 17:45:01

从 n3290,5.2.9 静态转换 [expr.static.cast]:

10 可以显式转换整型或枚举类型的值
为枚举类型。如果原始值不变,则该值不变
在枚举值(7.2)的范围内。否则,
结果值未指定(并且可能不在该范围内)。 [...]

枚举类型包括使用enum声明的类型和使用enum classenum声明的类型struct,标准分别将其称为无范围枚举和范围枚举。 7.2 枚举声明 [dcl.enum] 中有更详细的描述。

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

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

From n3290, 5.2.9 Static cast [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). [...]

Enumeration type comprises both those types that are declared with enum and those that are declared with enum class or enum struct, which the Standard calls respectively unscoped enumerations and scoped enumerations. Described in more details in 7.2 Enumeration declarations [dcl.enum].

The values of an enumeration type are not be confused with its enumerators. In your case, since the enumerations you declared all have int as their underlying types their range of values is the same as that of int: from INT_MIN to INT_MAX (inclusive).

Since 42 has type int and is obviously a value of int the behaviour is defined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文