fwiw, 
except for unscoped enums without a specified underlying type, all values of an enum's underlying type are valid, even if they don't match a given enumerator. 

a different approach would be to allow member functions for enum types (including a constructor for diy solving your problem).

Regards
Peter

sent from a mobile device so please excuse strange words due to autocorrection. 
Peter Sommerlad
peter.cpp@sommerlad.ch
+41-79-432 23 32

On 10 Aug 2022, at 14:12, a via Std-Proposals <std-proposals@lists.isocpp.org> wrote:


C++ proposal: Enumeration cast

(*Note: the enumerator type is the type of the enumerators of an enumeration, while the enumeration type is the enumeration itself)

Scoped enumerations require a `static_cast`to cast between enumerators("enumeration values") and the value types. However, they provide little safety checking, and can return undefined values in case of failure.
I propose a new cast `enumeration_cast` that throws an exception if the cast fails(no matching enumerators) instead of returning undefined values.
Moreover, if the enumerator types do not match or the cast parameter is `constexpr`(known at compile time) and the cast cannot succeed, the program shall be ill-formed.

Alternatives:
  • Return a "null value"(0 for scalar types and nullptr for pointer types) in case of failure and reject enumerations with classes without default constructors as the enumerator type. This implementation can be merged into `static_cast` if it is modified to do type checking for enumeration casts.
  • Make it a library function instead of a language feature. This also requires the program to be able to determine whether a value is an enumerator, and make type checking a language feature or leave out type checking.
  • Extend `static_cast`. Let an enumeration specify a default enumerator(`=default`) that defaults to the first enumerator(casts to empty enumerations cannot succeed and shall be ill-formed). Then, if casting from the enumerator type to the enumeration type, if no enumerators match or the default enumerator matches, the default enumerator is returned. If the types do not match, the cast shall be ill-formed.
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals