mardi 5 novembre 2019

How to restrict conversion from int to enum class?

If I have a enum class like this:

enum class Weekday {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}

and I have a conversion from int to Weekday:

Weekday day = static_cast<int>(value);

To check that the value provided for conversion is valid, I should have the code:

if (value != 0 && value != 1 && value !=2 && value !=3 && value != 4 && value != 5 && value != 6) { 
  do_conversion(value); 
}

It's so ugly. Is there any good way to do this?

Aucun commentaire:

Enregistrer un commentaire