I have an enum class as defined here
// namespace Types
enum class MessageType : uint32_t
{
COMPUTE_SUM_MESSAGE = 1
};
I want a function that can take an enum value and convert it to a byte array. I tried to use underlying_type to convert my enum value from a MessageType to an uint32_t but I get a no suitable constructor exists to convert it.
void ConvertMessageTypeToByteArray(Types::MessageType message_type)
{
using MessageTypeUnderlying = std::underlying_type<Types::MessageType>;
// Can not static cast the message_type to MessageTypeUnderlying
MessageTypeUnderlying data = static_cast<MessageTypeUnderlying>(message_type);
}
Is it possible to do something similar to this? I would like to have message_type as an unsigned 32 bit integer, which is its underlying type.
Your
usingstatement is wrong. It is definingMessageTypeUnderlyingas an alias for thestd::underlying_typestruct itself, not the enum's actual underlying type that it represents. Thus, you get the error when you try to cast an enum value to the struct type. The compiler's full error message should be pointing this out to you.To fix this, you need to instead define
MessageTypeUnderlyingas an alias for the type that is specified by thestd::underlying_type::typefield:Alternatively, in C++14 and later, you can use the helper
std::underlying_type_talias instead:That being said, C++23 adds
std::to_underlying(), which does exactly what you are trying to do manually: