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:
- Can you assign a default enum value for failed casts in c++?
- How to cast int to enum in C++?
- What happens if you static_cast invalid value to enum class?
Aucun commentaire:
Enregistrer un commentaire