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_field
I find the following function underlying_cast useful when having to serialise enum values correctly.
namespace util
{
namespace detail
{
template
using UnderlyingType = typename std::underlying_type::type;
template
using EnumTypesOnly = typename std::enable_if::value, E>::type;
} // namespace util.detail
template >
constexpr detail::UnderlyingType underlying_cast(E e) {
return static_cast>(e);
}
} // namespace util
enum SomeEnum : uint16_t { A, B };
void write(SomeEnum /*e*/) {
std::cout << "SomeEnum!\n";
}
void write(uint16_t /*v*/) {
std::cout << "uint16_t!\n";
}
int main(int argc, char* argv[]) {
SomeEnum e = B;
write(util::underlying_cast(e));
return 0;
}