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

后端 未结 4 592
再見小時候
再見小時候 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条回答
  •  -上瘾入骨i
    2021-01-28 21:19

    That's the feature. Scoped enumerations are not implicitly convertible to integers, so you can't use them in lieu of integers. They are strongly typed by design. If you want the implicit conversion, use unscoped enumerations.

    enum MsgType : int {
      Output = 1,
      Input  = 2,
      Debug  = 3
    };
    enum MsgSender : int {
      A = 1,
      B = 2,
      C = 3
    };
    

    Scoping and the specification of an underlying type are orthogonal.

    Alternatively, if you only want some operations to be defined, while the enumerations remain strongly typed in general, you can overload the appropriate operators to accomplish that

    int operator<<(MsgType, int); // etc
    

    But if I would not want them to be convertible, why would i specify the type to be int

    To ensure a certain layout. To follow a specific ABI. To allow forward declaring the type.

提交回复
热议问题