Domanda

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.

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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!
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top