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
source share