Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from int to enum class type possible?

Tags:

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 ?

like image 278
A 786 Avatar asked Nov 05 '18 04:11

A 786


People also ask

Can you cast int to enum C++?

C++ Explicit type conversions Enum conversions static_cast can convert from an integer or floating point type to an enumeration type (whether scoped or unscoped), and vice versa. It can also convert between enumeration types.

Can I convert int to enum C#?

Use the Type Casting to Convert an Int to Enum in C# The correct syntax to use type casting is as follows. Copy YourEnum variableName = (YourEnum)yourInt; The program below shows how we can use the type casting to cast an int to enum in C#. We have cast our integer value to enum constant One .

Can you typecast an enum?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

What is the difference between a class enum and a regular enum?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


Video Answer


1 Answers

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 
like image 80
tangy Avatar answered Sep 20 '22 19:09

tangy