Boost logo

Boost :

From: Greg Colvin (gcolvin_at_[hidden])
Date: 2000-01-18 15:11:01


From: Valentin Bonnard <Bonnard.V_at_[hidden]>
> First, happy new year everyone !

Thank you.
 
> Braden N. McDaniel wrote:
>
> > Is there any way to downcast a shared_ptr? That is, the effect of
> >
> > shared_ptr<Base> base(new Base);
> > shared_ptr<Derived> derived(base);
>
> I don't want to be able to write that w/o causing the
> compiler to complain !

Agreed.

> Sadly, new style casts can't be overloaded.

Yes, it is unfortunated.

> When similar functionnality was desired, Matt Austern
> proposed in London the use of do_static_cast,
> do_const_ etc for generalised allocator::pointer.
> I tend to like that.

I didn't like it, and argued that it was not necessary
for allocator::pointer. But shared_ptr never did meet
the requirements for allocator::pointer anyway.

> I propose (untested code):

Do we really need anything beyond dynamic cast? The reinterpret
cast is too dangerous, and it seems that static cast is already
provided for:
   shared_ptr<Derived> derived(new Derived);
   shared_ptr<Base> base(derived);

I recall proposing an auto_ptr::dyn_cast() member function
once apon a time, but nothing came of it. I plan to add one to
shared_ptr at the next opportunity.

> #define DEFINE_PSEUDO_CAST(THE_CAST) \
> template <typename To, typename From> \
> shared_ptr<To> do_ ## THE_CAST ## _cast (const shared_ptr<From>& p) \
> { \
> ++*p.pn; \
> return shared_ptr<To> (THE_CAST ## _cast<To*> (p.px), p.pn); \
> }
>
> DEFINE_PSEUDO_CAST(const)
> DEFINE_PSEUDO_CAST(static)

I don't think the macros are worth the bother for such small
functions.

> template <typename To, typename From>
> shared_ptr<To> do_dynamic_cast (const shared_ptr<From>& p)
> {
> if (To* pto = dynamic_cast<To*> (p.px))
> {
> ++*p.pn;
> return shared_ptr<To> (pto, p.pn);
> }
> else
> return shared_ptr<To> ();
> }
>
> With
>
> friend template <typename To, typename From>
> shared_ptr<To> do_dynamic_cast (const shared_ptr<From>& p);
> friend template <typename To, typename From>
> shared_ptr<To> do_const_cast (const shared_ptr<From>& p);
> friend template <typename To, typename From>
> shared_ptr<To> do_static_cast (const shared_ptr<From>& p);
>
> With the appropriate two args ctor:
>
> private:
> shared_ptr(T* px_, long* pn_)
> : px(px_), pn(pn_) {}
>
> (In the long term (next standard revision) someone might
> propose the overloading of casts in C++, just like other
> operators.)

Good idea. In the meantime we could provide do_*_cast for
built in pointers as well.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk