Mr. Boy
Mr. Boy

Reputation: 63720

A template class that only accepts enum type arguments?

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)

Upvotes: 2

Views: 814

Answers (2)

Marek R
Marek R

Reputation: 37657

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;
};

Upvotes: 4

Sebastian Redl
Sebastian Redl

Reputation: 71939

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.

Upvotes: 8

Related Questions