Reputation: 63720
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_if
with 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
Reputation: 37657
template<class T, typename = std::enable_if_t<std::is_enum_v<T>>>
class MyClass
{
std::map<T,std::string> mContents;
};
Upvotes: 4
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