mardi 14 juin 2016

How to safely cast integral types to scoped enums


C++11 scoped enums are great, you should use them whenever possible. However, sometimes you need to convert an integer to a scoped enum value (say if you are getting it from user input).

Is there a safe way to do this and detect when the value is not valid (i.e., outside the permitted values of the enum)?

I believe just using static_cast leads to undefined behavior if the integer is not valid. Is there a generic way of doing that does not require writing a conversion function for each scoped enum type by hand (and that needs to be updated every time you add a new value to the enum)?


Aucun commentaire:

Enregistrer un commentaire