Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-04-01 10:19:23

Ben Young wrote:
> Hi,
> I was wondering whether anyone had thought about adding a rebind
> nested template class to the boost ptrs, similar to those used by
> allocators.
> A situation has recently occurred where I need to get a ptr to a
> derived class from a pre to a base class, where the ptr to the base
> class is used
> a typedef e.g
> struct Base {};
> typedef boost::shared_ptr<Base> BasePtr;
> void func(const BasePtr& base)
> {
> }
> struct Derived : public Base {};
> typedef boost::shared_ptr<Derived> DerivedPtr;
> ^^^^^^^^^^^^^^^^^^^^^^^^^^
> Don't want to have to do this
> func(DerivedPtr(new Derived)) ....... etc
> The reason I dont want to have to do the second typedef is that we
> have a number of smart pointer classes of our own, and the type of
> the BasePtr should be an implementation detail.

Looks like you need the typedef template feature we keep hearing about. ;-)

One way to emulate this functionality is to use

template<class T> struct ptr
    typedef shared_ptr<T> type;

and express BasePtr and DerivedPtr as ptr<Base>::type and

However... my own experience with substituting different smart pointers in
such a way has been negative. The code usually depends on a particular
feature of shared_ptr (or other_ptr); this Isn't Supposed To Happen but it
almost always does.

So I've switched to the longer shared_ptr<Base> form, without the BasePtr
typedef. True, I have to do a global search and replace to change the smart
pointer type, but I need to review the code anyway to get rid of the subtle

Boost list run by bdawes at, gregod at, cpdaniel at, john at