Denis Steinman
Denis Steinman

Reputation: 7799

C++ 11 How to get enum class value by int value?

Can I get enum class variant by my int variable value? Now, I have so enum class:

enum class Action: unsigned int {
REQUEST,
RETURN,
ISSUANCE
};

And I need get this value from database value (database returns unsigned int). How to optimal make it? Now, just I use switch for each variant, but it's a stupidity. Please, explain me!

Upvotes: 9

Views: 17368

Answers (2)

billz
billz

Reputation: 45410

You can even write a generic convert function that should be able to convert any enum class to its underlying type(C++14):

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

With C++11

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

Upvotes: 13

I quite like the switch, because it means you can add a default: assert(!"Bad value in database"); line. On the other hand:

unsigned int ui = ... ;
auto action = static_cast<Action>(ui);

will work too.

Upvotes: 10

Related Questions