如果只需要一个成员专业化,如何避免重复整个类模板

时间:2012-10-16 10:38:37

标签: c++ templates specialization

假设你有:

template<class T>
class A {
  template<class T1> 
  void foo(const T1& t1) {}

  //
  // Lots of other definitions (all templated)
  // 
};

并且您希望专注foo(const T1&),但仅适用于专门的A<bool>。像这样:

template<>
class A<bool> {
  template<class T1> 
  void foo(const T1& t1) {
    // Code for specialized A<boo>::foo
  }

  //
  // Repeating the former definitions, how to avoid this ??
  // 
};

但要实现这一点,我必须复制在类模板class A中定义的所有代码,并将其再次包含在class A<bool>中。

我试图只定义成员专业化:

template<>
void A<bool>::template<class T1> foo(const T1&) {}

这两项都不起作用:

template <class T1> void A<bool>::foo(const T1&) {}

但是编译器不喜欢它。 处理此代码重复的方法是什么?

2 个答案:

答案 0 :(得分:7)

语法?见this answer。尝试:

template<>
template<typename T1>
void A<bool>::foo(const T1&){}

您当然不需要复制整个班级模板。

答案 1 :(得分:0)

您可以提供函数和类模板,然后定义几个typedef:

template<class T, class TArg> 
class A 
{   
    void foo(const TArg& arg) {}

    // Lots of other definitions (all templated)
};

typedef A<MyType, MyType> NormalClass;
typedef A<MyType, bool>   BoolClass;