C++ 如何使用模板参数专门化模板类的成员
我有一个带有int和template参数的模板类。 现在我想专门化一个成员函数:C++ 如何使用模板参数专门化模板类的成员,c++,templates,template-specialization,C++,Templates,Template Specialization,我有一个带有int和template参数的模板类。 现在我想专门化一个成员函数: template <int I> class Default{}; template <int N = 0, template<int> class T = Default> struct Class { void member(); }; // member definition template <int N, template<int> clas
template <int I> class Default{};
template <int N = 0, template<int> class T = Default> struct Class
{
void member();
};
// member definition
template <int N, template<int> class T> inline void Class<N, T>::member() {}
// partial specialisation, yields compiler error
template <template<int> class T> inline void Class<1, T>::member() {}
模板类默认值{};
模板结构类
{
无效成员();
};
//成员定义
模板内联void类::成员(){}
//部分专业化,产生编译器错误
模板内联void类::成员(){}
有人能告诉我这是否可能,以及我在最后一行中做错了什么吗
编辑:我要感谢大家的投入。由于我还需要一些T的专门化,所以我选择了纳瓦兹建议的解决方案,并专门对整个类进行了研究,因为它只具有一个成员函数和一个数据成员。C++中的< P>不允许部分地专门化函数;您只能部分地专门化类和结构。我相信这也适用于成员函数。不能对单个成员函数进行局部专门化,必须对整个类进行专门化
template <int I> class Default{};
template <int N = 0, template<int> class T = Default> struct Class
{
void member();
};
// member definition
template <int N, template<int> class T> inline void Class<N, T>::member() {}
// partial specialization
template <template<int> class T> struct Class<1, T>
{
void member() {}
};
模板类默认值{};
模板结构类
{
无效成员();
};
//成员定义
模板内联void类::成员(){}
//部分专业化
模板结构类
{
无效成员(){}
};
查看本文:
它非常小,并且有很好的代码示例。它将解释空间模板函数专门化的问题,并展示其他解决方法。由于这是不允许的,这里有一个解决方法:
template <int I> class Default{};
template <int N = 0, template<int> class T = Default>
struct Class
{
void member()
{
worker(int2type<N>()); //forward the call
}
private:
template<int N> struct int2type {};
template<int M>
void worker(const int2type<M>&) //function template
{
//general for all N, where N != 1
}
void worker(const int2type<1>&) //overload
{
//specialization for N == 1
}
};
模板类默认值{};
模板
结构类
{
无效成员()
{
worker(int2type());//转发调用
}
私人:
模板结构int2type{};
模板
void worker(const int2type&)//函数模板
{
//所有N的常规值,其中N!=1
}
void worker(const int2type&)//重载
{
//N==1的专门化
}
};
其思想是,当N=1时,函数调用worker(int2type())
将解析为第二个函数(专门化),因为我们正在传递类型int2type
的实例。否则,将解析第一个通用函数