Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely convert int to enum

Tags:

c++

enums

c++11

I would like to know if there is any clever trick how to safely convert integer into enum. Before you vote that this is duplicate, I'm not asking about how to convert (int i; Enum e = static_cast<Enum>(i) is easy). I'm asking how to do it safely, verifying that resulting value really is in the enum.

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 valid value from the enum. Best way I came up with 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 probably put together some macros to make this easier but it still looks dumb.

So is there any "standard" way to do it?

Thanks

like image 694
graywolf Avatar asked Jul 28 '15 13:07

graywolf


1 Answers

If you do not have to convert the numeric value as well, I'd 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 least that prevents some common mistakes like forgetting to change either the case or the return value or simply looking up the wrong numeric value. Also it's much more refactoring friendly (think about changing the numeric value - after all you define an enum so that you don't have to change the value in more than one place).

Unfortunately that still isn't very nice, but its the best way I know. Well, unless you want to use X macros.

like image 110
Paul Groke Avatar answered Oct 03 '22 18:10

Paul Groke