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

rit*_*ter 6 c++ templates specialization

假设你有:

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

  //
  // Lots of other definitions (all templated)
  // 
};
Run Code Online (Sandbox Code Playgroud)

而且你想专攻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 ??
  // 
};
Run Code Online (Sandbox Code Playgroud)

但为了使其工作,我必须复制在类模板中定义的所有代码class A并再次包含它class A<bool>.

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

template<>
void A<bool>::template<class T1> foo(const T1&) {}
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

template <class T1> void A<bool>::foo(const T1&) {}
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*obH 7

句法?看到这个答案.尝试:

template<>
template<typename T1>
void A<bool>::foo(const T1&){}
Run Code Online (Sandbox Code Playgroud)

您当然不需要复制整个类模板.