Possible Duplicate:
Specialization of templated member function in templated class
template <class T>
class MyClass
{
template <int N>
void func() {printf("unspecialized\n");}
};
template<class T>
template<>
MyClass<T>::func<0>()
{
printf("specialzied\n");
}
这是行不通的。是否可以专门化模板类的模板方法?
无法按要求完成。出于某种原因(我不确定基本原理)显式(即完整)成员模板的特化仅在封闭类也是显式时才允许(即完全)特化。此要求在语言标准中明确说明(请参阅 C++98 中的 14.7.3/18、C++03 和 C++11 中的 14.7.3/16)。
同时,成员 类 模板的部分特化是允许的,这在许多情况下可以用作一种变通方法(尽管是一种丑陋的方法)。但是,显然,它只适用于成员类 模板。当涉及到成员函数 模板时,必须使用替代解决方案。
例如,一个可能的解决方法是将调用委托(delegate)给模板类的静态成员并专门化该类(这通常被推荐为比函数模板专门化更好的主意 http://www.gotw.ca/publications/mill17.htm )
template <class T>
class MyClass
{
template <int N, typename DUMMY = void> struct Func {
static void func() { printf("unspecialized\n"); }
};
template <typename DUMMY> struct Func<0, DUMMY> {
static void func() { printf("specialized\n"); }
};
template <int N> void func() { Func<N>::func(); }
};