当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to call a method from parent classes that are instances of the same template [boost::enable_shared_from_this]

问题描述:

I have the following code.

class A: public boost::enable_shared_from_this<A> {

public:

virtual ~A() {}

boost::shared_ptr<A> returnMe() {

return shared_from_this();

}

};

class B: public A, public boost::enable_shared_from_this<B> {

boost::shared_ptr<B> returnMe() {

return shared_from_this();

}

};

gcc complains that the shared_from_this is ambiguous.

* In this case, is it safe to use boost::enable_shared_from_this<B>::shared_from_this() or

this->boost::enable_shared_from_this<B>::shared_from_this()

in the returnMe of B?

* Both A and B inherited from enable_shared_from_this with different parameters. Does it seem correct? Or I need to do something else?

If B does not inherit enable_shared_from_this, using shared_from_this() in B returns shared_ptr<A>. If so, is it safe to static_pointer_cast it to be shared_ptr<B>?

网友答案:

Did you try changing to something like return enable_shared_from_this<B>::shared_from_this(); ?

网友答案:

There are two bases that provide shared_from_this, but the types of the bases is distinct and thus you can use that to disambiguate:

shared_ptr<B> returnMe() {
   return static_cast<boost::enable_shared_from_this<B>*>(this)->shared_from_this();
}

That being said, the design might be a bit more complicated than what you want, in particular returnMe is not a virtual function (and cannot be, different non-covariant return type), which means that if you pass B to a function that takes a reference or pointer to A and they call shared_from_this() it will get the wrong version of the object.

While shared_ptr supports aliasing, and there is no technical reason, the interfaces don't support the configuration of enable_shared_from_this<A> to yield a shared_ptr<A> that can share ownership with the shared_ptr<B> that is managing the whole object.

If you can make the base pure virtual (remove the enable_shared_from_this and the returnMe functions) you will have a cleaner interface, less confusing as of what might work and how.

分享给朋友:
您可能感兴趣的文章:
随机阅读: