Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Enum value to integer in "Enum" and "Enum Class"

What is the difference between the Enum and Enum Class and how to converting Enum value to the integer in "Enum" and "Enum Class"?

like image 308
Mohammad reza Kashi Avatar asked Jul 26 '26 19:07

Mohammad reza Kashi


2 Answers

C++ has two kinds of enum:

enum classes
Plain enums
Here are a couple of examples on how to declare them:

 enum class Color { red, green, blue }; // enum class
 enum Animal { dog, cat, bird, human }; // plain enum 

What is the difference between the two?

enum classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)

Plain enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types

in the Enum:

enum type{x=10, y, z=50, j};

int value = x;

in the Enum Class:

enum class type{x=10, y, z=50, j};

int value = static_cast<int>(type::x);
like image 100
Mohammad reza Kashi Avatar answered Jul 28 '26 10:07

Mohammad reza Kashi


As of C++23 there's a library function, std::to_underlying, for converting enum class values to their underlying value.

int main ()
{
    enum class Foo {a, b, c, d, e, f};

    return std::to_underlying(Foo::f); // returns 5
}

https://godbolt.org/z/PE35eq78j

https://en.cppreference.com/w/cpp/utility/to_underlying

like image 34
Elliott Avatar answered Jul 28 '26 09:07

Elliott