![](/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.