0

I would like to convert an int to a C++11 scoped enum value. For example, I may read in integer values from a database or XML file and convert these to scoped enum values within my C++ application.

What is the best way to deal with integer values that are not defined within the scoped enum?

Consider the following code, which runs on VS2013.

#include <iostream>

enum class Fruit : int { Apple=0, Pear=1, Orange=2 };

int main(int argc, char* argv[])
{
    int n=3;
    Fruit fruit = static_cast<Fruit>(n);
    std::cout << "The value of n is: " << static_cast<int>(fruit) << std::endl;

    return 0;
}

The output is: The value of n is: 3

However, 3 is not a predefined constant value of Fruit. Is the above code correct C++11?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Jamerson
  • 474
  • 3
  • 14

0 Answers0