模板是否可以根据枚举值进行特化
#include <type_traits>
template<typename T, typename = void>
struct Specialize
{
};
template<typename T>
struct Specialize<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
void convert() { }
};
enum E
{
};
int main()
{
Specialize<E> spec;
spec.convert();
}
// My doubt: is below code valid? if not how to achieve this?
enum E
{
E1,
E2
};
int main()
{
Specialize<E, E1> spec;
spec.convert();
}
这是对以下问题的回答的后续问题。
How can I partially specialize a class template for ALL enums?
我已经从上面链接的问题的答案中复制粘贴了代码。
我的更改出现以下错误。
error: type/value mismatch at argument 2 in template parameter list for _template<class T, class>
最佳答案
// My doubt: is below code valid?
Specialize<E, E1> spec;
简短回答:否。
长答案。
您已经定义了Specialized
作为模板 struct
接收两个类型模板参数
template<typename T, typename = void>
struct Specialize
{
};
E
是一种类型但是 E1
是一个值。
if not how to achieve this?
如果你想要你的 struct
/class
接收作为模板参数的类型和该类型的值,从而实现 struct
的特化/class
iff(当且仅当)类型是枚举,您必须添加 typename = void
作为第三个模板参数
template<typename T, T Val, typename = void>
struct Specialize
{
};
template<typename T, T Val>
struct Specialize<T, Val, typename std::enable_if<std::is_enum<T>::value>::type>
{
void convert() { }
};
从 C++17 开始,您还可以使用 auto
作为模板值的类型并删除第一个模板参数
template<auto Val, typename = void>
struct Specialize
{
};
template<auto Val>
struct Specialize<Val, std::enable_if_t<std::is_enum_v<decltype(Val)>>>
{
void convert() { }
};
-- 编辑 --
OP 要求
how would we define the function "convert" outside the struct/class?
不幸的是,在这种情况下,我没有找到避免 std::enable_if
的方法。重复
template <typename T, T Val>
struct Specialize<T, Val,
typename std::enable_if<std::is_enum<T>::value>::type>
{ void convert(); };
template <typename T, T Val>
void Specialize<T, Val,
typename std::enable_if<std::is_enum<T>::value>::type>::convert ()
{ };
关于c++ - 我怎样才能部分特化枚举值的类模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645173/