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

后端 未结 4 588
再見小時候
再見小時候 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 20:58

    Type safety is the main reason to use the new scoped enums (perhaps the name is a bit misleading). If you merely want an enum that is scoped and can implicitly convert to integers you can wrap it in a struct or namespace:

    struct MsgSender {
       enum Values {
          A = 1,
          B = 2,
          C = 3
       };
    };
    

    Downside is that the type is now MsgSender::Values, but the values are MsgSender::A etc.

    For a scoped enum you have to static_cast to the std::underlying_type to get the integer.

提交回复
热议问题