mardi 28 juillet 2015

Safely convert int to enum

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

Aucun commentaire:

Enregistrer un commentaire