返回shared_ptr时如何完成协变返回类型? [英] How to accomplish covariant return types when returning a shared_ptr?

查看:158
本文介绍了返回shared_ptr时如何完成协变返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using namespace boost;

class A {};
class B : public A {};

class X {
  virtual shared_ptr<A> foo();
};

class Y : public X {
  virtual shared_ptr<B> foo();
};

返回类型不是协变的(因此也不合法),但是如果我使用的是原始指针,它们将是协变的.解决这个问题的普遍接受的成语是什么?

The return types aren't covariant (nor are they, therefore, legal), but they would be if I was using raw pointers instead. What's the commonly accepted idiom to work around this, if there is one?

推荐答案

我认为解决方案根本上是不可能的,因为协方差取决于与智能指针不兼容的指针算法.

I think that a solution is fundamentally impossible because covariance depends on pointer arithmetic which is incompatible with smart pointers.

Y::fooshared_ptr<B>返回给动态调用者时,必须在使用前将其强制转换为shared_ptr<A>.就您而言,B*可以(可能)被简单地重新解释为A*,但是对于多重继承,您将需要一些魔术来向C ++讲述static_cast<A*>(shared_ptr<B>::get()).

When Y::foo returns shared_ptr<B> to a dynamic caller, it must be cast to shared_ptr<A> before use. In your case, a B* can (probably) simply be reinterpreted as an A*, but for multiple inheritance, you would need some magic to tell C++ about static_cast<A*>(shared_ptr<B>::get()).

这篇关于返回shared_ptr时如何完成协变返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆