Unable to compile with inheritance of shared_from_this

119 views Asked by At

I'm using an home made shared_from_this class (CEnableSharedFromThis) because I'm under C++03 and I can't use boost on my project.

I have a class A which look like this :

class A : virtual CEnableSharedFromThis<A>
{
...
}

and class B like that :

class B : public A, virtual CEnableSharedFromThis<A>
{
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis());
   }
}

I see some people that have an error with an ambigous method. So I use virtual inheritance and I don't have this error.

But I have a new one that I can't give up in the foo() method.

The compiler says :

error: cannot convert from base CEnableSharedFromThis<A> to derived type A via virtual base CEnableSharedFromThis<A>

So I try the following foo() method :

   void foo()
   {
      Poco::SharedPtr<B> b(B::sharedFromthis());
   }

But it changes nothing.

Any idea ?

EDIT :

Following your recommandations I remove the inheritance of CEnableSharedFromThis of B and change foo() function like that :

class B : public A
{
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis().cast<B>());
   }
}
1

There are 1 answers

0
Puppy On

Override it and use static_pointer_cast instead.

class B : public A
{
   Poco::SharedPtr<B> sharedFromThis() {
       return Poco::StaticPointerCast<B>(CEnableSharedFromThis<A>::sharedFromThis());
   }
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis());
   }
}

This is assuming the existence of an analogous Poco::StaticPointerCast to std::static_pointer_cast.