2011-09-26 162 views
6

我有一个带有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提出的解决方法,并专门研究整个班级,因为它只有一个成员函数和一个数据成员。

回答

6

你不能部分地专门化一个单一的成员函数,你必须为整个类做这件事。

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

在C++中,您不允许部分专门化一个函数;你只能部分地专门化类和结构。我相信这也适用于成员函数。

3

由于这是不允许的,这里是一个解决办法:

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>类型的实例。否则,第一个,一般的功能将被解决。