Can an enum class be converted to the underlying type?

I think you can use std::underlying_type to know the underlying type, and then use cast:

#include <type_traits> //for std::underlying_type

typedef std::underlying_type<my_fields>::type utype;

utype a = static_cast<utype>(my_fields::field);

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 like enum 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:

template<typename E>
constexpr auto to_integral(E e) -> typename std::underlying_type<E>::type 
{
   return static_cast<typename std::underlying_type<E>::type>(e);
}

then use it:

auto value = to_integral(my_fields::field);

auto redValue = to_integral(Color::Red);//where Color is an enum class!

And since the function is declared to be constexpr, you can use it where constant expression is required:

int a[to_integral(my_fields::field)]; //declaring an array

std::array<int, to_integral(my_fields::field)> b; //better!

Leave a Comment