dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Safeguard Your enums: Make Them Strongly-Typed-3 : Page 3


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


Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Thanks for your registration, follow us on our social networks to keep up-to-date