Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 877
user877329 Avatar asked Dec 07 '22 02:12

user877329


1 Answers

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!
like image 71
Praetorian Avatar answered Dec 21 '22 23:12

Praetorian