Re: Two parent classes each with boost::enable_shared_from_this
In article <eskaje$nj$1@inews.gazeta.pl>, <"limcore@gazeta.pl"> wrote:
How to solve following problem:
I have two base classes A1 and A2, each must be able to return this as a
shared_ptr - it have a boost::enable_shared_from_this
Next they have a son B and its son C.
In C I want to get this as shared_ptr<A1> (and later dynami cast it into
C and use it) and also I want to be able to get this in form of
shared_ptr<C> (well - same thing as previous with casting)
A1 A2 - two parents, they must have enable_shared_from_this
| |
| |
\ /
B - B class
|
C - C class
now in C I need to get pointer to this as shared_ptr<A1>
and later I need to dynamic cast it into shared_ptr<C>
well if
struct A1 {};
struct A2{};
struct B:A1,A2{};
struct C:B,boost::enable_shared_from_this<C>
{
void foo()
{
boost::shared_ptr<A1> a1=shared_from_this();
//...
boost::shared_ptr<A2> a2=shared_from_this();
// ...
boost::shared_ptr<C> c = shared_from_this();
// ...
}
};
this works but no virtual hellos to prevent the which hello problem.
<begin code>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <exception>
#include <iostream>
struct Base
{
virtual ~Base(){}
};
struct A1:public virtual Base
{
void hello() {std::cout << "A1\n";}
};
struct A2:public virtual Base
{
void hello() {std::cout << "A2\n";}
};
struct B: public A1,public A2
{
void hello() {std::cout << "B\n";}
};
class C:public B,public boost::enable_shared_from_this<C>
{
public:
void foo()
{
boost::shared_ptr<A1> a1 = this->shared_from_this();
a1->hello();
boost::shared_ptr<A2> a2 = this->shared_from_this();
a2->hello();
boost::shared_ptr<Base> base = this->shared_from_this();
boost::shared_ptr<B> b = this->shared_from_this();
b->hello();
boost::shared_ptr<C> c = this->shared_from_this();
}
};
int main() try
{
boost::shared_ptr<C> c(new C);
c->foo();
std::cout << "done\n";
}
catch(std::exception const &x)
{
std::cerr << x.what() << '\n';
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]