Reflection TS: static reflection of enums (and other types)
Reflection TS, particularly [reflect.ops.enum]/2 of the latest version of the Reflection TS draft offers the get_enumerators
TransformationTrait
operation:
[reflect.ops.enum]/2
template <Enum T> struct get_enumerators
All specializations of get_enumerators<T>
shall meet the
TransformationTrait
requirements (20.10.1). The nested type named
type
designates a meta-object type satisfying
ObjectSequence
, containing elements which satisfy Enumerator
and
reflect the enumerators of the enumeration type reflected by T
.
[reflect.ops.objseq] of the draft covers ObjectSequence
operations, where particularly [reflect.ops.objseq]/1 covers the get_size
trait for extracting the number of elements for a meta-object satisfying ObjectSequence
:
[reflect.ops.objseq]/1
template <ObjectSequence T> struct get_size;
All specializations of get_size<T>
shall meet the
UnaryTypeTrait
requirements (20.10.1) with a base characteristic of
integral_constant<size_t, N>
, where N
is the number of elements in
the object sequence.
Thus, in Reflection TS were to be accepted and implemented in its current form, the number of elements of an enum can be computed, at compile time, as follows:
enum class Example { A, B, C, D, E };
using ExampleEnumerators = get_enumerators<Example>::type;
static_assert(get_size<ExampleEnumerators>::value == 5U, "");
where we are likely to see alias templates get_enumerators_v
and get_type_v
to simplify the reflection further:
enum class Example { A, B, C, D, E };
using ExampleEnumerators = get_enumerators_t<Example>;
static_assert(get_size_v<ExampleEnumerators> == 5U, "");
Status on Reflection TS
As stated by Herb Sutter's Trip report: Summer ISO C++ standards meeting (Rapperswil) from the June 9, 2018 ISO C++ committee summer meeting, Reflection TS has been declared as feature-complete
Reflection TS is feature-complete: The Reflection TS was declared feature-complete and is being sent out for its main comment ballot over the summer. Note again that the TS’s current template metaprogramming-based syntax is just a placeholder; the feedback being requested is on the core “guts” of the design, and the committee already knows it intends to replace the surface syntax with a simpler programming model that uses ordinary compile-time code and not <>
-style metaprogramming.
and was initially planed for C++20, but it's somewhat unclear if Reflection TS will still have a chance to make it into the C++20 release.