Is there a way to convert an enum class
field to the underlying type? I thought this would be automatic, but apparently not.
enum class my_fields : unsigned { field = 1 };
unsigned a = my_fields::field;
That assignment is being rejected by GCC. error: cannot convert 'my_fields' to 'unsigned int' in assignment
.
Best Answer
I think you can use std::underlying_type to know the underlying type, and then use cast:
With this, you don't have to assume the underlying type, or you don't have to mention it in the definition of the
enum class
likeenum class my_fields : int { .... }
or so.You can even write a generic convert function that should be able to convert any
enum class
to its underlying integral type:then use it:
And since the function is declared to be
constexpr
, you can use it where constant expression is required: