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. - If you can offer a solution based on somewhat stronger assumptions (underlying type size, nature of the set of values covered by the enum identifiers, known last value etc.), but which is still a general template rather than a different per-enum implementation - that is a useful, albeit imperfect, answer.
See also:
As of C++23, no standard mechanism for obtaining a list of valid values for an enum exists.
However, it is possible to use some incredibly janky compiler-specific code to extract this information.
The magic_enum library implements this code for the mainstream compilers.