【问题标题】:Is there any way to create a pair of template class containing each other? [duplicate]有没有办法创建一对相互包含的模板类? [复制]
【发布时间】:2020-05-06 13:23:13
【问题描述】:

我想做这样的事情:

A.hpp:

template <class B>
class A{
  B* B;
};

B.hpp:

template <class A>
class B{
  A* a;
};

它总是失败..

【问题讨论】:

  • 你能给我们一个minimal reproducible example 失败的地方吗?
  • 你有一个循环依赖。您还应该考虑更改模板类型名,以免它们与实际的类名冲突。
  • A&lt;B&lt;A&lt;B&lt;A&lt;B&lt;..&gt;&gt;&gt;&gt;&gt;&gt;
  • 谢谢兄弟,我正在阅读那个主题@HTNW
  • 注意到template &lt;class B&gt; class A; 中的Bclass B 之间与int n = 42; void f(int n); 无关,因此您的代码按原样编译,class AB 是具有相似定义的类(仅更改成员名称)。

标签: c++


【解决方案1】:

您可以使用模板模板参数(如果适用):

template <template <typename> class C>
class A{
  C<A>* B;
};

template <template <typename> class C>
class B{
  C<B>* a;
};

所以,A&lt;B&gt;B&lt;A&gt; 都是有效类型。

【讨论】:

  • 谢谢,但这似乎不适合我的情况
猜你喜欢
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多