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.
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.