Safely convert int to enum

I would like to know if there is any clever trick how to safely convert an integer to an enumeration. Before you vote that it is a duplicate, I do not ask how to convert ( int i; Enum e = static_cast<Enum>(i) easily). I ask how to do this safely by checking that the final value is indeed in an enumeration.

Following code

 enum class E { A = 1, B = 2 }; int main(int, char **) { int i = 3; E e = static_cast<E>(i); } 

will compile (AFAIK), but e will not contain a valid value from the enumeration. The best way I've come across is something like

 switch (i) { case 1: return E::A; case 2: return E::B; default: throw invalid_argument(""); } 

which 1) doesn't look very smart 2) doesn't scale so well. I could perhaps collect some macros to make it easier, but it still looks dumb.

So, is there a โ€œstandardโ€ way to do this?

thanks

+4
source share
2 answers

If you do not need to convert the numeric value as well, I would suggest something like

 switch (i) { case static_cast<int>(E::A): case static_cast<int>(E::B): return static_cast<E>(i); default: throw invalid_argument(""); } 

At the very least, this prevents some common mistakes, such as forgetting to change case or return value, or just looking for the wrong numeric value. In addition, it is much more convenient when refactoring (think about changing a numerical value - in the end you define an enumeration so that you do not have to change the value in more than one place).

Unfortunately, this is still not very good, but this is the best way I know. Well, if you do not want to use X macros .

+5
source

I suggest you check out these two approaches,

wise_enum

  • Enum standalone intelligent library for C ++ 11/14/17. It supports all the standard functionality that you expect from the smart enum class in C ++.
  • Limitations: minimum C ++ 11 required.

Top listings

  • The compile-time enum reflective library with pure syntax, in one header file and without dependencies.
  • Limitations: based on macros, cannot be used inside a class.
0
source

All Articles