C++ – Conversion from int to Enum Class Type

c++castingstrongly-typed-enum

I have a situation using C++ language, where I have got integer values from 1 to 7 for input into a method for weekdays . As I can easily convert enum class type to integers using static_cast but converting from integer to an enum is a bit of problem. Question aroused – is it possible to convert a number to enum class type? Because in another method which generated integer would have to call enum class weekday input based method for weekday update.
That update method only takes enum class type i.e
enum class weekday
{
Monday =1,
.
.
Sunday
}

Method is void updateWeekday(weekday e).

Can anybody help with that please ?

Best Answer

Yes, you can convert both ways: int to enum class and enum class to int. This example should be self explanatory:

enum class Color{Red = 1, Yellow = 2, Green = 3, Blue = 4};
std::cout << static_cast<int>(Color::Green) << std::endl; // 3
// more flexible static_cast - See Tony's comment below
std::cout << static_cast<std::underlying_type_t<Color>>(Color::Green) << std::endl; // 3
std::cout << (Color::Green == static_cast<Color>(3)) << std::endl; // 1
std::cout << (Color::Green == static_cast<Color>(2)) << std::endl; // 0

You can try it yourself here.


[EDIT] Since C++23, we'll have available std::to_underlying (at <utility>), what will allow us to write:

std::cout << std::to_underlying(Color::Green) << std::endl; // 3