【问题标题】:Circular dependency in template classes模板类中的循环依赖
【发布时间】:2016-07-27 19:51:09
【问题描述】:

我在循环引用类型时遇到问题。对于以下内容的实现:

// Parent.h
template <typename OtherType>
class EnclosingType
{
public:
    typename OtherType type_;
};

class OtherType
{
public:
    EnclosingType & e_;
    OtherType (EnclosingType & e) : e_(e) {}
};

要求是OtherType 引用EnclosureType 的一个对象,这样它就可以调用EnclosureType 上的方法,而EnclosureType 可以调用OtherType 上的方法。主要目标是允许实现者提供他们自己的 OtherType 派生类型。

处理存在这种循环依赖的情况的最佳方法是什么? OtherType 的正确声明是什么? OtherType::EnclosureType 的正确声明是什么? Enclosure::OtherType::type_ 的正确声明是什么?我需要做的事情有可能吗?

谢谢。

【问题讨论】:

  • EnclosingType 不是类型;这是一个模板。它没有方法。 OtherType 也没有方法。我不明白你在做什么。
  • 检查 CRTP,它可能对这种情况有所帮助,但我不确定它是否能帮助您解决问题。 en.wikipedia.org/wiki/Curiously_recurring_template_pattern

标签: c++ templates circular-dependency


【解决方案1】:

如果我假设您希望 OtherType 包含对 EnclosingType&lt;OtherType&gt; 的引用,您可以执行以下操作:

// EnclosingType declaration
template <typename T>
class EnclosingType;

// OtherType definition
class OtherType
{
public:
  EnclosingType<OtherType> & e_;
  OtherType (EnclosingType<OtherType> & e) : e_(e) {}
};

// EnclosingType definition
template <typename T>
class EnclosingType
{
public:
    T type_;
};

您可以在OtherType 中使用EnclosingType 声明(与定义相反),因为您通过指针或引用来引用它。 EnclosingType&lt;OtherType&gt;的定义需要OtherType的定义,因为它是按值包含的。

【讨论】:

  • 谢谢,这很有帮助,我接受这个作为答案。但是,我会请求您的宽容,并稍微扩展一下这个问题。如果 EnclosureType 需要多个(有限)内部类型(例如,OtherType1、OtherType2),模式会是什么。在这种情况下,消费者可能只选择从 OtherType1 派生,并使用 OtherType2 的默认实现。持有对 EnclosureType 实例的引用的 OtherType{n} 实例的要求仍然存在。对此有何想法?
  • 那是另一个问题。请将其单独发布,以便其他人以后受益。
猜你喜欢
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
相关资源
最近更新 更多