|
Boost Users : |
Subject: Re: [Boost-users] shared_ptr downcast
From: Vincent Agnus (vincent.agnus_at_[hidden])
Date: 2008-12-23 10:55:48
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.
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 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