Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A template class that only accepts enum type arguments?

Tags:

c++

c++11

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)

like image 919
Mr. Boy Avatar asked Jun 06 '26 00:06

Mr. Boy


1 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.

like image 120
Sebastian Redl Avatar answered Jun 07 '26 14:06

Sebastian Redl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!