Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

c++11

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!

like image 660
Шах Avatar asked Dec 10 '15 10:12

Шах


People also ask

Can we get an enum by value?

Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Can you cast an enum class to int?

Strongly typed enums can NOT be converted to integers without an explicit cast. Weak enums can, however, as they will be automatically implicitly cast. So, if you'd like automatic implicit conversion to an int, consider using a C-style weak enum instead (see more on this in the "Going further" section below).


1 Answers

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);
}
like image 69
billz Avatar answered Oct 14 '22 05:10

billz