c++ - 部分模板特化

标签 c++ class templates template-specialization partial-specialization

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

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 的定义。

关于c++ - 部分模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7112680/

相关文章:

c++ - 技巧编译器用于编译 128 位整数的基本算术运算

class - 如何对具有多个参数列表的类进行模式匹配?

Javap Asciz 字符串

c++ - 在编译时获取函数名称?

c++ - 无法从 C++ 中的文本文件中读取

c++ - 动脉(静脉扩展)示例不起作用

c++ - 2个函数中的不同条件锁定

python - 为什么重写 __getattribute__ 来代理值会搞砸 isinstance?

c++ - 如何使用模板修复 'no match for ‘operator*’(操作数类型为 ‘Matrix<double, 2, 3>’ 和 ‘Matrix<double, 3, 2>’)'

c++ - 完美转运不取货方式