如何用模板模板参数专门化模板类的成员



我有一个模板类,有一个int和一个模板模板参数。现在我要专门化一个成员函数:

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() {}

谁能告诉我这是可能的,我做错了什么在最后一行?

编辑:我想感谢大家的意见。由于我还需要对某些T进行专门化,所以我选择不采用Nawaz建议的解决方法,而是对整个类进行专门化,因为它无论如何都只有一个成员函数和一个数据成员。

不能对单个成员函数进行部分特化,必须对整个类进行特化。

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() {}
};

由于这是不允许的,这里有一个解决方案:

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
     }
};

这个想法是,当N=1时,函数调用worker(int2type<N>())将解析到第二个函数(专门化),因为我们传递了类型int2type<1>的实例。否则,将解析第一个通用函数

在c++中不允许对函数进行部分专门化;您只能部分地专门化类和结构。我相信这也适用于成员函数

查看本文:http://www.gotw.ca/publications/mill17.htm

它非常小,并且有很好的代码示例。它将解释部分模板函数专门化的问题,并展示它的其他方法。

最新更新