简体   繁体   English

将范围枚举转换为int

[英]Convert scoped enum to int

Why cannot a scoped enum be converted to int implicitly? 为什么不能将带范围的枚举隐式转换为int? If I have 如果我有

enum class Foo:uint32_t{...};

Then I know that the integers covered by Foo is a subset of those covered uint32_t, so I should always be safe. 然后我知道Foo覆盖的整数是uint32_t覆盖的整数的子集,所以我应该总是安全的。 Am I missing some quirk here? 我在这里错过了一些怪癖吗? The opposite cannot be safe though. 但相反的情况并不安全。

Just because such a conversion can always succeed doesn't mean you want it to be implicit. 仅仅因为这样的转换总能成功并不意味着你希望它是隐含的。

The entire purpose of scoped enums is that they are distinct types that won't lead to confusing results during overload resolution. 范围枚举的整个目的是它们是不同的类型,在重载解析期间不会导致混乱的结果。

Being explicit is good. 明确是好的。

As LightnessRacesinOrbit explains in his answer , the whole purpose of scoped enums is to disallow implicit conversion to the underlying type. 正如LightnessRacesinOrbit在他的回答中解释的那样,范围枚举的整个目的是禁止隐式转换为基础类型。

You can convert them explicitly via a static_cast , but if what you desire is the ability to specify an underlying type, while allowing implicit conversions, you can do so with regular enums too, just remove the class keyword from the definition. 您可以通过static_cast显式转换它们,但如果您希望能够指定基础类型,同时允许隐式转换,您也可以使用常规枚举,只需从定义中删除class关键字。

enum class Foo1 : uint32_t{ THING };
enum /*class*/ Foo2 : uint32_t{ THING };

uint32_t conv1 = static_cast<uint32_t>(Foo1::THING);
uint32_t conv2 = Foo2::THING;  // <-- implicit conversion!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM