문제

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.

도움이 되었습니까?

해결책 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.

다른 팁

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!
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top