enum
This is one of those pages where I will not go into the full history of enum
.
It started with C, but so did most of the C++ language. In its original form, it was
a vestigal hangover from C -- little more than a list of names for integers. It seems
like the ones from textbooks looked like this:
enum { zero = 0, one, two, ten = 10 };
Most of the ones in code did, too, and it raised the question "What is the advantage over #define?
#define zero (0) #define one (1) #define two (2) #define ten (10)
The underlying truth of this presentation of enum
has a lot to do with
failure to adopt. The underlying truth being that enum
was little more than
an integer tarted up for the type-safe, object oriented zealots. The veneer of type safety
could be eroded by the simplest of statements:
if (x > two && x < ten) ...
The new world order of C++11 has arrived.
If you want type safety, try the class
keyword in the enum context:
enum class X { ... one, two ... }; .. X myEnumObj;
The compiler will never accept implicit conversions to integers of your objects
of this type. Additionally, accidental (or intentional) use of the scope names for the
values the enum
may take will not be allowed to migrate their way into
inappropriate situations. You will get a compilation error.
Although the above is the big change, there are a couple of others. enum
is now a name that provides a scope of its own, so the names that appear inside the
braces above are named X::one
and X::two
preventing
collisions between common names (that always seem to be the ones we choose).
Additionally, it is possible to specify the underlying variety of "int
"
that is being used. This can be done by this syntax of using the colon after the type name.
enum class X : unsigned long long { ... };
Last updated 2014-07-19T15:44:11+00:00.
Links to the standard
A discussion of enum
can be found in section 7.2.
Benefits
The extension and more precise definition of enums is welcome, and the manner in which it was accomplished (assuring and ensuring that the old code doesn't break) is similarly a relief. These changes should encourage the use of enums.
Risks
My personal concern is that few people will learn the finer points, and those
programmers will back away from the new feature and return to the old enum,
which was hardly more than a #define
.