部分模板专业化

Enr*_*ata 7 c++ templates class partial-specialization template-specialization

我有一个模板类的场景

template<typename X, typename Y>
class Foo
{
 typedef Y::NestedType Bar;

 int A (Bar thing);
 void B();
 int C(X that);

 // other stuff
};
Run Code Online (Sandbox Code Playgroud)

然后我希望A()方法在X是给定类型时具有不同的行为(但是B和C可以保持不变,而实际代码实际上有大约10种其他方法,其中一些方法非常冗长,经常调整..所以我宁愿避免进行全班专业化并复制和粘贴完整的类实现)

我继续写道:

template<typename T>
int Foo<MyType, T>::A(Bar thing);
Run Code Online (Sandbox Code Playgroud)

但是我的编译器(clang 163.7.1)甚至拒绝将其视为任何类型的模板特化.

在我编写代码的方式中是否隐藏了一些语法错误,或者这种编码风格是无效的C++?不幸的是,即使其他编译器确实支持这个成语,我的公司仍然坚持使用clang.

感谢您的帮助.

Joh*_*itb 7

使用重载

template<typename X, typename Y>
class Foo
{
 // allows to wrap up the arguments
 template<typename, typename>
 struct Types { };

 typedef Y::NestedType Bar;

 int A (Bar thing) {
   return AImpl(thing, Types<X, Y>());
 }

 void B();
 int C(X that);

 // other stuff
private:
  template<typename X1, typename Y1>
  int AImpl(Bar thing, Types<X1, Y1>) {
    /* generic */
  }

  template<typename Y1>
  int AImpl(Bar thing, Types<SpecificType, Y1>) {
    /* special */
  }
};
Run Code Online (Sandbox Code Playgroud)

您不能部分专门化类模板的成员.你写A的是类模板本身的部分特化的成员函数的定义.