Specializing a templated member of a template class
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Specialization of templated member function in templated class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | template <class T> class MyClass { template <int N> void func() {printf("unspecialized ");} }; template<class T> template<> MyClass< T >::func<0>() { printf("specialzied "); } |
这是行不通的。 可以专门化模板类的模板方法吗?
无法按照要求完成。 由于某些原因(我不确定原理),只有在封闭类也被明确(即完全)专门化时,才允许成员模板的明确(即完全)专门化。 在语言标准中明确说明了此要求(请参阅C ++ 98,C ++ 03中的14.7.3 / 18和C ++ 11中的14.7.3 / 16)。
同时,允许成员类模板的部分专业化,这在许多情况下可以用作解决方法(尽管很丑陋)。 但是,显然,它仅适用于成员类模板。 对于成员函数模板,必须使用替代解决方案。
例如,一种可能的解决方法是将调用委派给模板类的静态成员并对其进行专门化处理(通常建议将其作为比对功能模板进行专门化处理更好的主意http://www.gotw.ca/publications/ mill17.htm)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | template <class T> class MyClass { template <int N, typename DUMMY = void> struct Func { static void func() { printf("unspecialized "); } }; template <typename DUMMY> struct Func<0, DUMMY> { static void func() { printf("specialized "); } }; template <int N> void func() { Func<N>::func(); } }; |