只接受枚举类型参数的模板类?
鉴于这个伪存根类:
template<class T>
MyClass
{
std::map<T,std::string> mContents;
};
有没有办法只允许T是枚举类型?我试图了解这个问题和链接页面中讨论的内容,我是否可以使用std::enable_ifwithstd::is_enum但我无法轻松查看它是否适用于我的情况(模板专业化 enum)
回答
你不需要任何enable_if技巧。您只需要一个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;
};
在 C++20 中,您可以改用约束。