如何用模板解决这个循环继承问题?

How to resolve this circular inheritance issue with template?

我有以下 class:

template<class T>
class Base: public Root //this one abstract
{
    std::vector<std::shared_ptr<T>> components;
}

template<class T>
class Derived : Base<T> //this one not abstract
{
 //stuff
}

我正在建造:

Derived<Base<Root>> myDerived;
std::shared_ptr<Base<Root>> ptr_base;
ptr_base.reset(&myDerived); // -> ERROR

编译器给我:

error C2664: 'std::_Ptr_base<_Ty>::_Reset0' : cannot convert parameter 1 from 'model::Derived <T> *' to 'model::Base<T> *'

所以编译器似乎不明白 Derived<Base<Root>> 也是 Base<Root> 因为我想做的是:

1.Base<Root> is Root 来自 Base

的定义

2.Derived<T>Base<T> 来自 Derived<T>

的定义

所以 Derived<Base<Root>>Base<Root>

有什么提示吗?

谢谢。

您似乎希望 Derived 的模板参数,即 Base<Root>,是 'upcasted' 到 Root。强制转换适用于对象,但不适用于模板参数:特化模板定义了一种不同于其他特化的新类型。

Derived<Base<Root>> 可以转换为 Base<Base<Root>>,但不能转换为 Derived<some-ancestor-of-Base<Root>>.

一般来说,如果Derived继承自Base,则AnyClass<Derived>不能转换为AnyClass<Base>

Derive<T>Based<T>,因此 Derived<Base<Root>>Base<Base<Root>>

现在的问题是:Base<Base<Root>>Base<Root>吗?

换句话说:Base<Base<Root>> 是否派生自 Base<Root>

或等价地:Base<A> 是否派生自 Base<B>,A=Base<Root> 且 B=Root?

没有。 A 派生自 B,但 Base<A> 不派生自 Base<B>.

就像 vector<X> 不派生自 vector<Y> 一样,即使 X 继承了 Y。