Using scoped enumerations
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.
How to do it...
- Prefer to use scoped enumerations instead of unscoped ones.
- In order to use scoped enumerations, you should declare enumerations using
enum class
orenum struct
:
enum class Status { Unknown, Created, Connected }; Status s = Status::Created;
Note
The enum class
and enum struct
declarations are equivalent, and throughout this recipe and the rest of the book, we will use enum class
.
How it works...
Unscoped enumerations have several issues that are creating problems for developers:
- They export their enumerators...