【发布时间】:2023-03-28 12:10:01
【问题描述】:
我无法为这个问题想出一个好名字,对此我深表歉意。如果看完后你有更好的名字,请告诉我。无论如何,我有一些类似于以下的代码:
// BaseFamily.h
template<typename T>
class BaseChild {
T parent;
}
class BaseParent {
virtual BaseChild<BaseParent>* createChild() = 0;
}
.
// DerivedFamily.h
class DerivedParent;
class DerivedChild: public BaseChild<DerivedParent> {}
class DerivedParent
: public BaseParent
{
BaseChild<BaseParent>* createChild() override {
return new DerivedChild();
// error: Cannot initialize return object of type 'BaseChild<BaseParent> *' with an rvalue of type 'DerivedChild *'
}
}
上面是两组父子循环引用。此外,后者的集合继承自前者的父母和孩子。继承的东西之一是用于创建子对象的函数,该函数被覆盖以返回 DerivedChild 而不是 BaseChild。
这似乎应该至少接近作为指向 BaseChild 的指针应该能够处理指向 DerivedChild 的指针,但这些似乎不能与我所知道的任何语法互换。
问一个问题:我怎样才能创建一个返回类型为BaseChild<BaseParent>* 的函数以允许DerivedChild<DerivedParent>*?
编辑:我可能找到了线索derivation template classes。但是CRTP似乎并不能解决这个问题。
【问题讨论】:
-
为什么
BaseChild不能只持有指向BaseParent的引用/指针作为成员而不是类型参数? -
如果是这样,那将如何解决这个问题? (我最初尝试过,但也许你有更好的方法)
标签: c++ templates inheritance forward-declaration rvalue