2016-07-27 94 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

這是另一個問題。請單獨發佈,以便其他人可以在以後獲益。 –