|
Boost : |
From: Raffaele Romito (berserker_r_at_[hidden])
Date: 2006-01-10 10:58:23
I often need to retrive a shared_ptr of a derived that inherit from a
"shared_enabled" base class, for example:
class A : public boost::enable_shared_from_this<A>
{
public:
A() { }
virtual ~A() { }
void some_a_method()
{
boost::shared_ptr<A> ptr = shared_from_this();
}
};
class B : public A
{
public:
void some_b_method()
{
boost::shared_ptr<B> ptr =
boost::dynamic_pointer_cast<B>(shared_from_this());
}
};
Actually I'm using an helper class to "hide" the dynamic_pointer_class
stuff:
template <typename T>
class shared_enabled : public boost::enable_shared_from_this<T>
{
public:
shared_enabled() { }
virtual ~shared_enabled() { }
inline boost::shared_ptr<T> this_ptr() { return shared_from_this(); }
inline boost::shared_ptr<T const> this_ptr() const { return
shared_from_this(); }
template <typename I>
inline boost::shared_ptr<I> this_ptr() { return
boost::dynamic_pointer_cast<I>(shared_from_this()); }
template <typename I>
inline boost::shared_ptr<I const> this_ptr() const { return
boost::dynamic_pointer_cast<I const>(shared_from_this()); }
};
Deriving A from shared_enabled it's easier (my opinion) to write
"some_b_method":
void some_b_method()
{
boost::shared_ptr<B> ptr = this_ptr<B>();
}
What about a simple extension in the enable_shared_from_this class?
template <typename I>
inline shared_ptr<I> shared_from_this()
{
return dynamic_pointer_cast<I>(shared_from_this());
}
template <typename I>
inline shared_ptr<I const> shared_from_this() const
{
return dynamic_pointer_cast<I const>(shared_from_this());
}
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk