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!
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.
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.
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).
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With