为什么允许使用任意值初始化枚举类临时变量? [英] Why is initialization of enum class temporaries with arbitrary values allowed?

查看:68
本文介绍了为什么允许使用任意值初始化枚举类临时变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CppCon 2014的一次演讲中,我碰到了一些类似以下的代码,这让我很困惑。观众不加评论地接受了它,因此我认为它是合法的。

I came across some code like the following in one the CppCon 2014 talks that confused the heck out of me. The audience accepted it without comment, so I presume that it's legal:

enum class Foo { Bar };

Foo const v1 = Foo(5);

问题是:为什么要编译?我希望编译失败,并抱怨我们无法将int转换为Foo。下面略作修改的行失败,并出现预期错误:

The question is: why does this compile? I would expect compilation to fail and complain that we can't convert an int to a Foo. The slightly modified line below fails with the expected error:

Foo const v1(5);


推荐答案

范围枚举类型的隐式基础类型为 int ,假设未指定其他基础类型。可以表示所有类型为 int 的值。

Scoped enumeration types have an implicit underlying type of int, assuming no other underlying type is specified. All possible values of type int can be represented.

7.2p5:


[...]对于作用域枚举类型,如果未明确指定,则基础类型为 int 。在这两种情况下,基础类型
被称为 fixed 。 [...]

[...] For a scoped enumeration type, the underlying type is int if it is not explicitly specified. In both of these cases, the underlying type is said to be fixed. [...]

7.2p8:


对于基础类型固定的枚举,该枚举的值是基础类型的值。 [...]

For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. [...]

任何可以由枚举表示的整数值都可以显式转换为该枚举类型,例如@哥伦布在他现在删除的答案中指出:

And any integral value that can be represented by the enumeration can be explicitly converted to that enumeration type, as @Columbo had pointed out in his now-deleted answer:

5.2.9p10:


整数或枚举类型的值可以显式转换为枚举类型。如果原始值在枚举值(7.2)的范围内,则该值不变。 [...]

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). [...]

由于注释中存在一些混淆,这意味着:

Since there is some confusion in the comments about what that means:


enum class Foo { Bar };

Foo const v1 = Foo(5);


是明确定义的。不是未定义,不是未指定,甚至不是实现定义的。我引用的标准部分解释如下:

is well-defined. Not undefined, not unspecified, not even implementation-defined. The parts of the standard I quote explain that:


  1. Foo 的基础类型是 int ,并且基础类型是固定的。

  2. Foo int 的值。

  3. 由于 5 在枚举值的范围,该值在转换后保持不变。

  1. The underlying type of Foo is int, and that the underlying type is fixed.
  2. The values of Foo are the values of int.
  3. Since 5 is in the range of the enumeration values, the value is unchanged by the conversion.

这篇关于为什么允许使用任意值初始化枚举类临时变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆