Tuesday, November 8, 2011

Strongly typed enum in C++11

C++11 introduces the enum class which are strongly typed means, they are type-safe. Enum's are interpreted as integers and thus you can compare enumeration values from completely different enumeration types.

enum class MyEnum
{
VALUE1,
VALUE2 = 10,
VALUE3
};
So this is not legal in C++11:
if (MyEnum::VALUE3 == 11) {...}

By default, the underlying type of an enumeration value is an integer, but this can be changed as follows:


enum class MyEnumLong : unsigned long
{
LVALUE1,
LVALUE2 = 10,
LVALUE3
};
Enum class type is user defined so we can define operators. By default Enum class has only assignment, initialization, and comparisons operator.
enum class color { green, yellow, red };
color& operator++(color& t)
// prefix increment: ++
{
switch (t) {
case color::green: return t = color::yellow;
case color::yellow: return t = color::red;
case color::red: return t = color::green;
}
}
color next = ++light; // next becomes color::green

No comments:

Post a Comment