lundi 4 juin 2018

Proper way to construct strongly typed enum from integer

Given that static_cast<MyEnum>(userInt) leads to Undefined Behaviour (or not specified depending on which standard), what's the proper way to construct a strongly typed enum from an integer inputted by the user?

Also, I'd like to set it to a default value if the inputted value is not mapped in the enum.

One solution is:

switch (userInt)
{
    case 1:
        return myEnum1;
    case 2:
    default:
        return myEnum2;
}

But I don't like that I have to remember to update it if I changed the enum values.

Aucun commentaire:

Enregistrer un commentaire