c++ - 专门化模板类的模板化成员

标签 c++ templates

<分区>

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

关于c++ - 专门化模板类的模板化成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10178598/

相关文章:

c++ - 友元模板函数的正确语法

c++ - 如何部分特化类模板非类型参数

c++ - 如何保证使用编译时常量初始化堆栈变量

c++ - 从其他库创建库 : is it possible?

c++ - 通用 Makefile 忽略变量

c++ - 在 Windows 8 上编译 boost 1.55.0 库

c++ - C++模板特化/部分和全部

c++ - qi::parse boost 改变开始迭代器

c++ - 从智能指针确定类型

c++ - 将函数放入模板