I am a beginner in C++ programming.
Today I come across a new topic: strongly typed enum
. I\'ve researched it a bit but till now I am unable to find ou
The enum classes ("new enums", "strong enums") address three problems with traditional C++ enumerations:
enums
implicitly convert to int
, causing errors when someone does not want an enumeration to act as an integer.enums
export their enumerators to the surrounding scope, causing name clashes.enum
cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible. enum class
("strong enums") are strongly typed and scoped:
enum Alert { green, yellow, orange, red }; // traditional enum
enum class Color { red, blue }; // scoped and strongly typed enum
// no export of enumerator names into enclosing scope
// no implicit conversion to int
enum class TrafficLight { red, yellow, green };
Alert a = 7; // error (as ever in C++)
Color c = 7; // error: no int->Color conversion
int a2 = red; // ok: Alert->int conversion
int a3 = Alert::red; // error in C++98; ok in C++11
int a4 = blue; // error: blue not in scope
int a5 = Color::blue; // error: not Color->int conversion
Color a6 = Color::blue; // ok
As shown, traditional enums work as usual, but you can now optionally qualify with the enum's name.
The new enums are "enum class" because they combine aspects of traditional enumerations (names values) with aspects of classes (scoped members and absence of conversions).
Being able to specify the underlying type allow simpler interoperability and guaranteed sizes of enumerations:
enum class Color : char { red, blue }; // compact representation
enum class TrafficLight { red, yellow, green }; // by default, the underlying type is int
enum E { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U }; // how big is an E?
// (whatever the old rules say;
// i.e. "implementation defined")
enum EE : unsigned long { EE1 = 1, EE2 = 2, EEbig = 0xFFFFFFF0U }; // now we can be specific
It also enables forward declaration of enums:
enum class Color_code : char; // (forward) declaration
void foobar(Color_code* p); // use of forward declaration
// ...
enum class Color_code : char { red, yellow, green, blue }; // definition
The underlying type must be one of the signed or unsigned integer types; the default is int
.
In the standard library, enum
classes are used for:
: enum class errc
;
: enum class pointer_safety { relaxed, preferred, strict };
: enum class io_errc { stream = 1 };
: enum class future_errc { broken_promise, future_already_retrieved, promise_already_satisfied };
Several of these have operators, such as ==
defined.