A template class that only accepts enum type arguments?

Viewed 213

Given this pseudo stub class:

template<class T>
MyClass
{
 std::map<T,std::string> mContents;
};

Is there a way to only allow T to be an enum type? I was trying to understand what was discussed in this question and linked pages, whether I can use std::enable_ifwith std::is_enum but I can't get my head round it easily to see if it translates to my case (Template specialization for enum)

2 Answers

You don't need any enable_if tricks. All you need is a static_assert:

template<class T>
class MyClass
{
  // pre-C++17:
  static_assert(std::is_enum<T>::value, "template argument must be enum");
  // C++17
  static_assert(std::is_enum_v<T>);
  std::map<T,std::string> mContents;
};

In C++20, you can use a constraint instead.

https://godbolt.org/z/4bvdrb

template<class T, typename = std::enable_if_t<std::is_enum_v<T>>>
class MyClass
{
    std::map<T,std::string> mContents;
};
Related