transform/convert enum type

How do we transform/convert enum type into any variable (int, char, etc) type in c++?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Example program
#include <iostream>

enum class Answer : int {
  Yes,
  No,
  Maybe,
  I_Dont_Know,
};

int main()
{
    int value = static_cast<int>(Answer::Maybe);
    std::cout << value << '\n';
}

2


More generic version with C++14:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Example program
#include <iostream>

// C++14 std::underlying_type

enum class Answer : int {
  Yes,
  No,
  Maybe,
  I_Dont_Know,
};

int main()
{
    auto value = static_cast<std::underlying_type<Answer>::type>(Answer::Maybe);
    std::cout << value << '\n';
}
Last edited on
Topic archived. No new replies allowed.