-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Modern C++ Programming Cookbook
By :

Enumeration is a basic type in C++ that defines a collection of values, always of an integral underlying type. Their named values, that are constant, are called enumerators. Enumerations declared with keyword enum
are called unscoped enumerations and enumerations declared with enum class
or enum struct
are called scoped enumerations. The latter ones were introduced in C++11 and are intended to solve several problems of the unscoped enumerations.
enum class
or enum struct
:enum class Status { Unknown, Created, Connected }; Status s = Status::Created;
The enum class
and enum struct
declarations are equivalent, and throughout this recipe and the rest of the book, we will use enum class
.
Unscoped enumerations have several issues that are creating problems for developers:
enum Status {Unknown, Created, Connected}; enum Codes {OK, Failure, Unknown}; // error auto status = Status::Created; // error
int
, unless the enumerator value cannot fit a signed or unsigned integer. Owing to this, forward declaration of enumerations was not possible. The reason was that the size of the enumeration was not known since the underlying type was not known until values of the enumerators were defined so that the compiler could pick the appropriate integer type. This has been fixed in C++11.int
. That means you can intentionally or accidentally mix enumerations that have a certain meaning and integers (that may not even be related to the meaning of the enumeration) and the compiler will not be able to warn you:enum Codes { OK, Failure }; void include_offset(int pixels) {/*...*/} include_offset(Failure);
The scoped enumerations are basically strongly typed enumerations that behave differently than the unscoped enumerations:
enum class Status { Unknown, Created, Connected }; enum class Codes { OK, Failure, Unknown }; // OK Codes code = Codes::Unknown; // OK
enum class Codes : unsigned int; void print_code(Codes const code) {} enum class Codes : unsigned int { OK = 0, Failure = 1, Unknown = 0xFFFF0000U };
int
. Assigning the value of an enum class
to an integer variable would trigger a compiler error unless an explicit cast is specified:Codes c1 = Codes::OK; // OK int c2 = Codes::Failure; // error int c3 = static_cast<int>(Codes::Failure); // OK