mardi 21 novembre 2023

Can I cast a number into an enum, safely, with a fallback value?

I would like to write something like:

template <typename E, E fallback>
E safe_cast_to_enum(std::underlying_type_t<E> e);

which, for an enum class (or just an enum?) E, casts e to a corresponding value of E, if such a value exists, and to value fallback otherwise.

Can I do this generically?

Notes:

  • I suspect the answer is negative until at least C++20, but regardless - please (also) answer using the earliest C++ version with which this is possible.
  • If you like, you may assume fallback is a 'valid' value of the enum, i.e. it has an associated named identifier.

See also:





Aucun commentaire:

Enregistrer un commentaire