Thursday 14 May 2015

Convert an enum class to its underlying_type

Generic helper function which takes any enum value and returns that value cast to its integral representation.

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);
}

Since it is constexpr it can be used as follows:

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

http://stackoverflow.com/questions/14589417/can-an-enum-class-be-converted-to-the-underlying-type