【问题标题】:partial template specialization部分模板特化
【发布时间】:2011-10-30 01:44:36
【问题描述】:

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

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卡住了。

感谢您对此的任何帮助。

【问题讨论】:

  • 我不知道这是否对您有帮助,但请记住,C++ 中不允许模板函数的部分特化(仅限模板类)。
  • 你必须先专攻这门课。
  • 你需要在类的其余部分或其函数中使用 X 的类型吗?如果没有,您可以使用模板函数。

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


【解决方案1】:

使用重载

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

【讨论】:

  • 我已经使用类层次结构解决了这个问题。我以前的 Foo 类变成了 Foo_base 类。然后,我有 class Foo : public Foo_base ,它只重新定义了构造函数和赋值运算符。然后,我的部分专业化是在类模板专业化 Foo : public Foo_base 中,它只从其父级重新定义 A() 方法(最终它所做的是 { thong = Something(thing) ; ParentClass::A(thong); })。这是相当多的打字,但可以完成工作。谢谢!
  • 无论如何,我希望能够“部分专门化类模板的成员”:-) 我不明白禁止这样做的意义。
猜你喜欢
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多