I think you can use std :: basic_type to find out the base 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);
However, you do not need to assume the base type, or you do not need to mention it in the definition of enum class as enum class my_fields : int { .... } or so.
You can even write a generator conversion function that should be able to convert any enum class into its main 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 as constexpr , you can use it where a constant expression is required:
int a[to_integral(my_fields::field)]; //declaring an array std::array<int, to_integral(my_fields::field)> b; //better!
Hope this helps.
Nawaz Jan 29 '13 at 18:16 2013-01-29 18:16
source share