我在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