C++ Logo


Advanced search

[std-proposals] Fwd: C++ proposal: Enumeration cast

From: a <programmer00001h_at_[hidden]>
Date: Wed, 10 Aug 2022 20:11:54 +0800
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
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.


   - 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
   - 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.

Received on 2022-08-10 12:12:08