I haven't found any wording in the C++11 standard that says unscoped enums are deprecated, but from a pragmatic perspective I'm wondering if they are still useful. A lot of people on my team have gotten in the habit of converting unscoped enums to scoped enums, but it's caused some headache:
class foo
{
public:
enum MyEnum { One, Two, Three };
};
They convert this to:
class foo
{
public:
enum class MyEnum { One, Two, Three };
};
Which means when these enumerators are used, instead of foo::One
, it looks like foo::MyEnum::One
. I've been asking the following best-practices:
- If you convert to scoped enum, move it out of classes and into global scope or namespace scope (to improve usability and avoid the latter usage example above).
- If you keep the enum unscoped, make sure it's in namespace/class/function/etc scope so that it doesn't conflict with other names.
The main difference between the two points is that for #1 we don't put them in classes, which otherwise adds some verbose indirection.
All of this seems like over complication, and seems like it would be much simpler to just keep enumerations already in classes as unscoped enums. What's the general best-practice approach for deciding between the two?
enum class
is everything you can read about why it was added; the disadvantage of switching toenum class
is everything you wrote above. That doesn't tell us what to do when writing our code from scratch, though. – StriateClass::Enumerator
. So, when all that changes is the addition of theclass
keyword, things become too verbose for no real reason:Class::Enumeration::Enumerator
– Firstratestatic-cast
any where – Polysyndetonstatic_cast
ing your scoped enums then you missed the point entirely and your code is wrong. – Striate