2016-07-27 95 views
0

我遇到了类型的循环引用问题。对于以下的implmentation:模板类中的循环依赖项

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

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

要求是OTHERTYPE采取EnclosingType的一个对象的引用,以便它可以调用EnclosingType方法和EnclosingType可以OTHERTYPE调用方法。主要目标是允许实施者提供他们自己的OtherType派生类型。

处理这种类型的循环依赖存在的情况下,最好的方法是什么?什么是OtherType的正确声明?什么是OtherType :: EnclosingType的正确声明? Enclosing :: OtherType :: type_的正确声明是什么?我甚至需要做甚么?

谢谢。

+1

'EnclosingType'不是一个类型;这是一个模板。它没有办法。 'OtherType'也没有方法。我不明白你想要做什么。 – melpomene

+0

检查CRTP,这可能对这种情况很有帮助,但我不太确定它是否会帮助您解决问题。 https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern –

回答

1

如果我让你想OtherType包含对EnclosingType<OtherType>基准假设下,你可以做到以下几点:

// 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<OtherType>的定义需要OtherType的定义,因为它包含它的值。

+0

谢谢,这很有帮助,我接受这个答案。不过,我会请你放纵一下,并将问题扩大一点。如果EnclosingType需要多个(有限)内部类型(例如OtherType1,OtherType2),则该模式会是什么样子。在这种情况下,使用者可能只会选择派生自OtherType1,并使用OtherType2的默认实现。持有对EnclosingType实例的引用的OtherType {n}实例的要求仍然存在。对此有何想法? – user1612443

+0

这是另一个问题。请单独发布,以便其他人可以在以后获益。 –