部分模板专门化

partial template specialization

本文关键字:专门化      更新时间:2023-10-16

有一个场景,其中有一个模板类

template<typename X, typename Y>
class Foo
{
 typedef Y::NestedType Bar;
 int A (Bar thing);
 void B();
 int C(X that);
 // other stuff
};

,然后我希望A()方法有一个不同的行为,当X是一个给定的类型(但B和C可以保持不变,实际的代码实际上有大约10个其他方法,其中一些是相当长的,并受到频繁的调整。所以我宁愿避免做一个完整的类专门化和复制&粘贴完整的类实现)

我继续写:

template<typename T>
int Foo<MyType, T>::A(Bar thing);

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

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

谢谢你的帮助。

使用重载

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 */
  }
};

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