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:
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.
- Strongly Typed Enums – Document No 1719 (open-std.org)
- auto & decltype (nullptr.me)
- better types in C++11 (cprogramming.com)
- enum classes – scoped and strongly typed (research.att.com)