C++11: enum classes

C++11 along with adding lot of cool stuff is also fixing up most of the ugliness with C++ language. One of my personal favourite is enum class. Enums in C++ are (shouldn’t I write were :)) not type-safe in-sense they are convertible to and from integers and you can’t scope them, which at times leads to ugly naming conventions.

C++11 addresses this limitation with enum classes, which makes enums strongly typed and scoped:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
enum class Colour
{
    Red,
    Green,
    Blue
};

int main()
{

    // lvalue of type Colour
    auto var = Colour::Red;

    //  cannot assign it to an int -- compilation failure
    int val = var;

    //  type-inferencing works correctly
    decltype(var) greenColor = Colour::Green;

    //  casting will work
    int val2 = static_cast(var);

    //  what is Red? undeclared identifier. nice
    //  compilation failure
    auto val3 = Red;

    //  can't compare enum-class and int
    //  we haven't defined operator==(Colour,int)
    auto areEqual = Colour::Red == 0;

    return 0;
}

With normal enums, you can access enumerators (eg. Red) directly in the surrounding scope (eg. within main). However, with enum classes, the strong scoping rules mean you have to use a scope qualifier to access the enumerator (eg. Colour::Red). This helps keep name pollution and the potential for name conflicts down.

The strong typing rules means that C++ will look for an explicitly defined comparison function to compare Color and Fruit. Since we haven’t defined an operator==(Colour, int) function, the compiler won’t understand how to compare a and b in any meaningful way, and this will cause a compile-time error to occur.

Related articles: