Boost logo

Boost :

From: martinschuerch_at_[hidden]
Date: 2001-07-13 02:34:05

> >> Sounds like a plan.
> >
> >I would very appreciate some downcast of shared_ptr in boost. At
> >moment I'm using a hack similar as posted in related mails. But
for a
> >proper solution there has to be some support of shared_ptr.
> >
> >Is there any work in progress for this subject?
> Why don't you post suggested code?
> --Beman

So here it is:

The template function shared_dynamic_cast<> delegates the work to the

template<class Q>
void downcasted_copy_to( shared_ptr<Q>& q ) const

that way no friend is used. VC would not support the partial
specialization (or is it overloading I never know) of
polymorphic_downcast<> and I like shared_ptr and the downcast to be
an unit without dependencies.
The suggested code isn't optimized for speed.


        template<class Q>
        void downcasted_copy_to( shared_ptr<Q>& q ) const
                Q* rawq = dynamic_cast<Q*>(px);
                if( !rawq || !px ) { q = shared_ptr<Q>(); }
                shared_ptr<Q> ptmp;
                ptmp.px = rawq;
       = pn;
                q.swap( ptmp );

"global" function:

template<class Tout,class Tin>
boost::shared_ptr<Tout> shared_dynamic_cast(
                         const boost::shared_ptr<Tin>& p )
        boost::shared_ptr<Tout> pout;
        return pout;

int test_main( int, char *[] ) // note the name!
        using namespace boost;

        shared_ptr<Base> pb( new Base );
        shared_ptr<Base> pb2d( new Derived );
// shared_ptr<Derived> pd( new Derived );
        shared_ptr<Derived> pd;

        pd = shared_dynamic_cast<Derived>(pb2d);
        pd = shared_dynamic_cast<Derived>(pb);
        BOOST_CRITICAL_TEST( pd == shared_ptr<Derived>() );

        return 0;

Thanks for feedback

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