用派生类的类型覆盖函数参数类型 [英] Override function parameter type with type of derived class
问题描述
我计划使用一种采用自己类型的参数的方法来创建一个接口(而不是c ++中的虚拟基类)。
I plan to create an interface (rather a virtual base class in c++) with a method that takes an argument of the own type.
class Base {
public:
virtual void seriousMethod(const Base &arg) = 0;
}
但是,派生类不应采用基类类型的参数,而应采用
The derived class should however take not an argument of the base class type but of the derived class type.
class Derived: public Base {
public:
virtual void seriousMethod(const Derived &arg) { /* ... */ }
}
我知道吗?我需要对基类进行模板化(例如 Base< Derived>
)还是有更清洁的解决方案?
How would I realize this? Would I have to template the base class (e.g. Base<Derived>
) or is there a cleaner solution?
推荐答案
您不能直接执行此操作。考虑这种情况:
You can't do this directly. Think about this case:
Base b;
Derived d;
Base& d_ref = d;
d_ref.seriousMethod(b); // What happens here?
在编译时,变量 d_ref
具有静态类型 Base
,因此根据 Base
的定义,它应该能够使用 b
作为 seriousMethod
的参数。
At compile-time, the variable d_ref
has static type Base
, so according to the definition of Base
, it should be able to take b
as a parameter to seriousMethod
.
但是在运行时,动态类型 d_ref
的值是 Derived
,因此根据 Derived $ c $的定义c>,它不能将
b
作为 seriousMethod
的参数。它不能将 b
转换为 Dervied
,因为它可能是直接的 Base
对象(如果 Base
不是抽象对象),或者它可能是从 Base
派生的其他一些类,与派生的
不同。
But at runtime, the dynamic type of d_ref
is Derived
, so it according to the definition of Derived
, it can't take b
as a parameter to seriousMethod
. It can't convert b
to Dervied
since it might be a straight Base
object (if Base
is not abstract), or it might be some other class derived from Base
that is not the same as Derived
.
您是正确的,假设唯一真正的解决方法是反复出现的模板模式,即将 Base
模板化并将 Dervied
定义为:
You are correct in assuming that the only real way to go about this is the curiously-recurring template pattern, i.e. templating Base
and defining Dervied
as:
class Derived : public Base<Derived> { ... }
这消除了上面说明的问题,因为每种类型均源自 Base< T>
将具有不同的基类,并且不会通过继承相互关联。
This removes the problem illustrated above, because each type derived from Base<T>
will have a distinct base class, and will not be related to one another through inheritance.
这篇关于用派生类的类型覆盖函数参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!