How can I specialize a class for enums of underlying type int?

  • A+
Category:Languages
#include <type_traits>  enum class MyEnum {     Hello };  template <typename T, typename Enable = void> class MyClass { public:     MyClass(T obj) : e(obj)     {}  private:     T e; };  template <typename T> class MyClass <T,      typename std::enable_if< std::is_enum<T>::value                               && std::is_same<typename std::underlying_type<T>::type,                                               int>::value>::type >  { public:     MyClass(T obj) : e(obj)     {}  private:     T e; };  int main() {     MyClass<MyEnum> c(MyEnum::Hello);     MyClass<int> c1(1); //does not compile due to std::underlying_type     return 0; } 

I would like to be able to specialize MyClass for enums of underlying type 'int'. I can't do that using std::underlying_type because it is only specific to enums. Any ideas on how I can proceed?


A simple enough solution to this quirk is to insulate std::underlying_type behind your own SFINAE-friendly trait:

template <class T, class = void> struct underlying_type {};  template <class T> struct underlying_type<     T,     typename std::enable_if<std::is_enum<T>::value>::type > {     using type = typename std::underlying_type<T>::type; }; 

Then your specialization can be written as:

template <typename T> class MyClass<     T,      typename std::enable_if<std::is_same<         typename underlying_type<T>::type,         int     >::value>::type > {     // ... }; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: