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:

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;
    //
}

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.