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 arithmetics. But why - since the enum is explicitly typed as int?
example:
enum class MsgType : int {
Output = 1,
Input = 2,
Debug = 3
};
enum class MsgSender : int {
A = 1,
B = 2,
C = 3
};
// later in code
int id = (MsgType::Input << 16) + (MsgSender::A);
produces
error C2678: binary '<<': no operator found which takes a left-hand operand of type 'MyClass::MsgType' (or there is no acceptable conversion)
This seems to be somewhat illogical to me.
Edit:
I am totally aware of the possillity to cast them. But if I would not want them to be convertible, why would i specify the type to be int
. Especially if the syntax suggest some kind of "inherited from int
"
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.