C++11 introduces what are known as scoped enums. These are enumerations whose members must be qualified with enumname::membername
. Scoped enums are declared using the enum class
syntax. For example, to store the colors in a rainbow:
enum class rainbow {
RED,
ORANGE,
YELLOW,
GREEN,
BLUE,
INDIGO,
VIOLET
};
To access a specific color:
rainbow r = rainbow::INDIGO;
enum class
es cannot be implicitly converted to int
s without a cast. So int x = rainbow::RED
is invalid.
Scoped enums also allow you to specify the underlying type, which is the type used to represent a member. By default it is int
. In a Tic-Tac-Toe game, you may store the piece as
enum class piece : char {
EMPTY = '\0',
X = 'X',
O = 'O',
};
As you may notice, enum
s can have a trailing comma after the last member.