2

I am looking for a safe and maintainable way to convert an int value to enum class. I know i can convert inegral values to enum class by simply using static_cast, but i want to make sure the value to be converted really has a representation in the enum class either before or after converting.

Everything that comes to mind right now is a switch statement that contains cases for all the entries of the enum class.

enum class Entries { A, B, C }

switch(number)
{
case static_cast<int>(Entries::A): return Entries::A;
case static_cast<int>(Entries::B): return Entries::B;
case static_cast<int>(Entries::C): return Entries::C;
default: // Handle error here
}

But this is not very maintainable as every time a new entry is added or an old entry deleted, this switch statement has to be changed. I am hoping for something i won't have to touch again even if the enum class changes.

Detonar
  • 1,409
  • 6
  • 18

2 Answers2

2

You can create both the enum and the switch statement with a macro, which allows you to safely add new values:

// In header file
#define ENUM_VALUES(x) \
  x(A) \
  x(B) \
  x(C)       

#define CREATE_ENUM(name) \
  name,

enum class Entries { ENUM_VALUES(CREATE_ENUM) }

// In source file
#define CREATE_SWITCH(name) \
  case static_cast<int>(Entries::name): return Entries::name;

switch(number)
{
ENUM_VALUES(CREATE_SWITCH)
default: // Handle error here
}

Based on this answer.

VLL
  • 9,634
  • 1
  • 29
  • 54
2

maybe you can use this

//define your enum here
#define MacFunction(XX) \
XX(TypeA,0)\
XX(TypeB,2)\
XX(TypeC,3)

enum class Entries{
#define EnumDef(Type,Number) Type = Number,
    MacFunction(EnumDef)

    Unexpected,
#undef EnumDef
};
Entries SafeCastFromInt( int n )
{
#define SafeCast( Type,_ ) case static_cast<int>(Entries::Type):return Entries::Type;
    switch( n )
    {
        MacFunction(SafeCast)
        default:
        std::cout<<"error cast:"<<n<<std::endl;
        break;
    }
    return Entries::Unexpected;
#undef SafeCast
}
int main()
{
    SafeCastFromInt(0);
    SafeCastFromInt(1);
    SafeCastFromInt(2);
}

output is

error cast:1
HongluWong
  • 119
  • 2