I wanted to change an old-style enum
to enum class : int
because of its own scope.
But the compiler complains about using the values in integer
You can't use c++11 scoped enums directly as int, but can cast it into int
.
Mainly because of type safety reason, unscoped enum can leak names inside the enums, and the scoped enum doest not have a risk of leak name, the names can only be visbile inside.
There are 2 kinds of enums in c++ so far.
C++98-style unscoped enums:
enum Color {Red, Green, Yellow};
,
which can implicit convert to int.
C++11 scoped enums: enum class{Red, Green, Yellow};
,
which cann't be implicit convert to int, can only use a cast to convert to other type, like static_cast
.
Scoped enums have 3 advantage comparing to unscoped enums:
Meanwhile, Unscoped enums are more flexible than scoped enums.
Both scoped enums and unscoped enums support specification of the underlying type, the default underlying type for scoped enums is int
. Unscoped enums have no default underlying type, which is compiler dependent, can be a char
or int
, according to the range of values.
enum class Color: std::uint8_t{Red, Green, Yellow}; // Definition
enum Color: std::uint8_t{Red, Green, Yellow}; // Forward Declaration
Unscoped enums may be forward-declared only if ther declaration sepcifies an underlying type.
In Practice, prefer scoped enums to unscoped enums.
See the book "Effective Modern C++" by Scott Meyers, item 10: prefer scoped enums to unscoped enums.