enum Classes
Appending the
class keyword to an enum declaration creates a strongly typed enum. Unlike a traditional enum, a strongly-typed enum isn't implicitly converted to integral types:
enum class Set //C++09 strongly-typed enum
{
E1,
E2,
E3 = 4,
E4 = 8
};
void g(Set s )
{
if( s > 10 ) // error, can't convert Set to int
Set s2=Set::E1; //OK
}
Strongly-typed enums are represented as
int by default. However, you can specify a different underlying type using inheritance-like syntax. For example, to specify an underlying type of
unsigned short for
Set, declare it like this:
enum class Set: unsigned short
{
E1,
E2,
E3 = 4,
E4 = 8
};
Scope
Strongly-typed enumerators' scope is restricted to their enclosing enumeration. It doesn't propagate to the enclosing scope. This property reduces the risk of name conflicts and ambiguities to a minimum. To refer to such enumerators from an external scope, use their qualified names:
enum class Set: char {E1, E2};
Set s=E1; //error, E1 isn't recognized in this scope
Set s=Set::E1; //OK, qualified enumerator used
Ease and Safety
Strongly typed enums can coexist with traditional enums. Therefore, legacy code will continue to work as expected even after this feature is added to C++. However, upgrading traditional enums to strongly-typed ones is an easy and welcome step. Simply add the
class keyword to the declarations of traditional enum types and recompile. To make your existing enums C++09-ready and facilitate future migration, you can use
conditional compilation for the time being:
#ifdef CPP09_STRONGLY_TYPED_ENUMS
#define CPP09_ENUM class
#else
#define CPP09_ENUM
#endif
enum CPP09_ENUM Color //traditional or strongly-typed
{
Red,
Green,
Blue
};