why can enum class values of type int not be used as int

后端 未结 4 591
再見小時候
再見小時候 2021-01-28 20:29

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

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 21:15

    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(my_color).

    Scoped enums have 3 advantage comparing to unscoped enums:

    1. Reduce namespace pollution;
    2. Strong type safety;
    3. Scoped enums may be forward-declared, unscoped enums needs additonal work to be forward-declared;

    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.

提交回复
热议问题