For one who has never written a line of C++11, and who has, at the moment, no opportunity to program in C++11, can you, in one short paragraph., tell me:
What is an "enum class" and why do we need it?
c++c++11enum-classenums
For one who has never written a line of C++11, and who has, at the moment, no opportunity to program in C++11, can you, in one short paragraph., tell me:
What is an "enum class" and why do we need it?
Best Answer
enum class
is called a scoped enumeration. It prevents polluting the namespace where the enumeration appears with the names of the enumerators.In C++03, you could do effectively the same thing by putting the
enum
inside a dedicatedclass
. Perhaps that's the source of the syntax, which is a bit confusing.Another difference is that the enumerators of such a type don't convert implicitly to
int
(static_cast<int>
is required). This may be seldom needed but it makes it safe to overload a function taking anint
argument with one takingenum
type. You can be sure theint
won't be called by accident. Or you can define pseudo-integral types with dedicatedoperator
functions, and be sure that built-in operators won't interfere.It's a bit annoying that these two unrelated differences come in the same package, and that you can't get an unscoped enumeration with no implicit conversion, but generally both changes are Good Things and
enum class
is a good default practice in C++11.EDIT: A scoped enumeration is defined like this:
and must be used with the scope resolution operator
::
like this:Note that the
::
operator also works with C++03 unscoped enumerations, so the second line above would work even if the first was missingclass
.This might be excessive detail, but
class
does not go into the elaborated-type-specifier if forward declaring the enumerated type, as inHowever, there is a construct new in C++11, the opaque-enum-declaration, which does include the
class
keyword and defines a complete type.The keyword
struct
can be substituted forclass
with no semantic difference.