【问题标题】:Mismatched type error between `BaseChild<BaseParent>*` and `DerivedChild<DerivedParent>*``BaseChild<BaseParent>*` 和 `DerivedChild<DerivedParent>*` 之间的类型不匹配错误
【发布时间】: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&lt;BaseParent&gt;* 的函数以允许DerivedChild&lt;DerivedParent&gt;*

编辑:我可能找到了线索derivation template classes。但是CRTP似乎并不能解决这个问题。

【问题讨论】:

  • 为什么BaseChild 不能只持有指向BaseParent 的引用/指针作为成员而不是类型参数?
  • 如果是这样,那将如何解决这个问题? (我最初尝试过,但也许你有更好的方法)

标签: c++ templates inheritance forward-declaration rvalue


【解决方案1】:
class BaseParent; // forward declaration

class BaseChild{
public:
  BaseChild(BaseParent* parent_)
    :parent(parent_)
  {}
  BaseParent* parent;
}

class BaseParent {
  virtual BaseChild* createChild() = 0;
}

class DerivedParent;
class DerivedChild: public BaseChild {
public:
  DerivedChild(DerivedParent* parent)
    :BaseChild(parent)
  {}
}

class DerivedParent
  : public BaseParent
{
  BaseChild* createChild() override {
    return new DerivedChild();  
  }
}

我不知道问题的上下文,所以我不确定这是否有帮助。

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 2019-05-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多