协方差的最好的解决方案

协方差的最好的解决方案

本文介绍了什么时候是C ++协方差的最好的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

于几小时前在这里提出并让我意识到
我从来没有在我自己的代码中实际使用协变返回类型。对于那些
不确定什么协方差,它允许(通常)虚拟
函数的返回类型不同,只要类型是相同的继承
层次结构的一部分。例如:

This question was asked here a few hours ago and made me realise thatI have never actually used covariant return types in my own code. For thosenot sure what covariance is, it's allowing the return type of (typically) virtualfunctions to differ provided the types are part of the same inheritancehierarchy. For example:

struct A {
   virtual ~A();
   virtual A * f();
   ...
};

struct B : public A {
   virtual B * f();
   ...
};

两个f()函数的不同返回类型称为协变。旧版本的C ++需要返回类型相同,所以B应该是这样:

The different return types of the two f() functions are said to be covariant. Older versions of C++ required the return types to be the same, so B would have to look like:

struct B : public A {
   virtual A * f();
   ...
};

所以,我的问题:任何人都有一个真实世界的例子,其中虚拟函数的协变返回类型

So, my question: Does anyone have a real-world example where covariant return types of virtual functions are required, or produce a superior solution to simply returning a base pointer or reference?

推荐答案

规范示例是 .clone() / .copy()方法。所以你总是可以做

The canonical example is a .clone()/.copy() method. So you can always do

 obj = obj->copy();

编辑:此克隆方法将在Object基类中定义(实际上是在Java中)。因此,如果克隆不是协变的,你将不得不强制转换,或者限制为根基类的方法(只有非常少的方法,比较副本的源对象的类)。

This clone method would be defined in the Object base class (as it actually is in Java). So if clone wasn't covariant, you would either have to cast, or would be restricted to methods of the root base class (which would have only very few methods, compared the class of the source object of the copy).

这篇关于什么时候是C ++协方差的最好的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:21