|
Boost Users : |
Subject: Re: [Boost-users] shared_ptr downcast
From: Jason Cipriani (jason.cipriani_at_[hidden])
Date: 2008-12-24 04:31:31
2008/12/23 Vincent Agnus <vincent.agnus_at_[hidden]>:
>
>
> Igor R wrote:
>>
>> 2008/12/23 Jason Cipriani <jason.cipriani_at_[hidden]>:
>>>
>>> If I have:
>>>
>>> class Base { };
>>> class Derived : public Base { };
>>>
>>> And a container, e.g.:
>>>
>>> std::vector<boost::shared_ptr<Base> > objs;
>>>
>>> How do I downcast to a shared_ptr<Derived>? E.g.:
>>>
>>> boost::shared_ptr<Derived> d = (boost::shared_ptr<Derived>)objs[0];
>>>
>>
>> Look at boost::static_pointer_cast
>
> using class polymorphism boost::dynamic_pointer_cast is better.
Thanks, this is exactly what I wanted.
Jason
>
>
> You can also iterate on our vector as if the elements are of type Derivated
> with a code like this :
>
>
> typedef std::vector<boost::shared_ptr<Base> > VectorBase;
>
> template < class SubClass>
> struct DownCaster
> : public std::unary_function< boost::shared_ptr< Base >, boost::shared_ptr<
> SubClass> >
> {
> boost::shared_ptr< SubClass> operator()(
> boost::shared_ptr< Base > obj ) const
> {
> return boost::dynamic_pointer_cast< SubClass >( obj );
> }
> };
>
> typedef typename boost::transform_iterator< DownCaster<Derived> ,
> VectorBase::iterator > CastIterator;
>
> CastIterator start( objs.begin() );
>
> boost::shared_ptr<Derived> d = *start; // is OK
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net