33

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 ?

2
  • 1
    Use static_cast? Commented Nov 5, 2018 at 4:46
  • static_cast is best option, or possibly create your own function that takes in an int and has a switch statement that checks all possible outputs and returns the enum for that integer, and you pass that result to the updateWeekday() function Commented Nov 5, 2018 at 4:54

1 Answer 1

42

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
Sign up to request clarification or add additional context in comments.

3 Comments

It's a nit pick, and a little tedious, but it's (arguably?) more maintainable to cast from an enum to its underlying type - e.g. static_cast<std::underlying_type_t<Colour>>(Colour::Green) - that way if Colour's underlying type changes later (whether due to a change to an explicitly specified underlying type in the enum definition, or one worked out by the compiler from the enumeration values) the cast won't break. Countering that, if you cast to underlying you run the risk of that being or becoming a char type and << considering it an ASCII value / not printing the integer value.
Thanks for mentioning it - I've added it to the answer. It is definitely more flexible.
when you static_cast<Color>(5), what did you get? This cast static_cast<int>(static_cast<Color>(5)) still gets me 5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.