简体   繁体   中英

Convert scoped enum to int

Why cannot a scoped enum be converted to int implicitly? 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. 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.

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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