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.