![](/img/trans.png)
[英]How to forward declare a template class and use it as a member data in C++?
[英]How to use forward declarations for a template class in a shared pointer (in C++)
我在Base.h中定義了一個基類Base
:
class Base
{ /* ... */ };
還有一個從Base
派生的類模板Child
,它在Child.h中定義:
#include "Base.h"
template <class T>
class Child : public Base
{ /* ... */ };
現在,我想在Base
類中創建一些工廠方法,這些方法應將std::shared_ptr
返回到Child
類。 為了避免循環依賴,我嘗試使用前向聲明。 因此, Base.h現在看起來像這樣:
class Child; // new forward declaration
class Base
{
/* ... */
// new factory method
static std::shared_ptr<Base> CreateChildInt(int i = 0)
{
return std::make_shared<Child<int>>(i);
}
};
但是, CreateChildInt()
的定義導致以下編譯器錯誤:
“錯誤C2947:期望'>'終止模板參數列表,找到'<'”
那么,這甚至有可能是我想要達到的目標嗎?
如果沒有,這種方法是否有任何解決方法/最佳做法?
編輯 :為什么我想將工廠方法放入Base
類而不是Child
的原因如下。 當我將工廠放入Child
我需要像下面這樣調用factory方法:
std::shared_ptr<Base> p = Child<int>::CreateChildInt(3);
但是,我想在此調用中省略模板類型<int>
,因此:
std::shared_ptr<Base> p = Base::CreateChildInt(3);
首先,您聲明了一個類,但是您定義的Child
實際上是一個模板。 聲明類模板的正確方法是:
template <class T>
class Child;
但是,僅靠正確的前向聲明並不能幫助您。 CreateChildInt::CreateChildInt
的實現必須知道Child
的完整定義,因為它創建了它的實例。 您也不能在Base
之前定義Child
,因為繼承也取決於完整的定義,因此最終會產生關鍵的依賴性。
解決方案:轉發聲明Child
,然后定義Base
但不要內聯定義Base::CreateChildInt
,然后定義Child
,最后定義Base::CreateChildInt
。
PS。 從OOP角度看,我懷疑基類成員函數的實現取決於子類。 我建議您考慮重新設計方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.