Roddy
Roddy

Reputation: 68023

Polymorphic casts with boost::shared_ptr

I'm familiar with boost's polymorphic_cast on normal pointers:

Base *base;

Derived *d = boost::polymorphic_cast<Derived>(base);

But, how to use it with boost::shared_ptr instead?

boost::shared_ptr<Base> base;

boost::shared_ptr<Derived> d = boost::?????(base);

Upvotes: 3

Views: 1983

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476970

Use boost::static_pointer_cast or boost::dynamic_pointer_cast, as analogues of the C++ casts static_cast and dynamic_cast:

boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(base);

// now "d" shares ownership with "base"

This just performs the respective cast on the underlying raw pointer.

(The same is true in the std namespace in the C++11 standard library and for the std::tr1 name­space in the TR1 library for C++03.)

Upvotes: 2

Related Questions