我在Base.h定義的基類Base
:如何在共享指針使用正聲明爲模板類(在C++)
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:期待 '>' 終止模板argument- list,found'<''
那麼這甚至可能是我想要實現的嗎?
如果沒有,這種方法是否有任何解決方法/最佳實踐?
編輯: 原因爲什麼我希望把工廠方法爲Base
類,而不是Child
如下。當我把工廠變成Child
我需要調用工廠方法是這樣的:
std::shared_ptr<Base> p = Child<int>::CreateChildInt(3);
不過,我想省略模板類型<int>
在這個調用,因此:
std::shared_ptr<Base> p = Base::CreateChildInt(3);
您需要'template class Child;'。 –
爲什麼這個工廠是'Base'的一部分?通常OO基礎班不應該知道他們的孩子。 – melpomene
@Matthias我不會把它放在任何一堂課。無論如何它都是靜態的;爲什麼不把它放在外面? – melpomene