Home:ALL Converter>Infer enum class type from enum class value template parameter?

Infer enum class type from enum class value template parameter?

Ask Time:2016-12-05T00:38:33         Author:Ross Bencina

Json Formatter

Is it possible to create a template that infers the underlying enum class type of an enum class value template parameter? I am looking to do something like the following non-working pseudo-example:

enum class MyEnumClass { e1, e2, e3 };

template<enum class T X> MyTemplate { // wrong syntax. want to specify X, infer T
     using enum_class_type = T;
     static constexpr enum_class_type value = X;
};

Which I would like to be instantiatable with only one parameter, e.g. MyTemplate<MyEnumClass::e1>:

static_assert( std::is_same<MyTemplate<MyEnumClass::e1>::enum_class_type, MyEnumClass>::value );
static_assert( MyTemplate<MyEnumClass::e2>::value == MyEnumClass::e2 );

I know that the following works, but it requires me to explicitly specify the enum class type as a second template parameter:

template<typename EnumClass, EnumClass X>
struct EnumValue {
    using enum_class_type = EnumClass;
    static constexpr enum_class_type value = X;
};
// usage: EnumValue<MyEnumClass, MyEnumClass::e1>::enum_class_type

Author:Ross Bencina,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40960936/infer-enum-class-type-from-enum-class-value-template-parameter
yy