Boost logo

Boost :

From: John Maddock (John_Maddock_at_[hidden])
Date: 2000-08-07 05:37:46

Hi all,

While messing about with the is_convertible type-traits template it occured
to me that there is an interesting use for shared_ptr.

Currently shared_ptr uses an implicit static_cast in it's template member
functions - that prevents shared_ptr from being used as fully as possible
with polymorphic types (where a dynamic_cast would open up the range of
available convertions). I've been messing with the following cast, which
for want of a better name I've called "maybe_cast" - it's intended as an
implementation detail rather than a cast in it's own right so don't worry
about the name - anyway it switches between static_cast and dynamic_cast
depending upon whether an implicit conversion is possible:

namespace detail{

template <bool>
struct cast_selector
   template <class T, class U>
   static T do_cast(U u, T) { return dynamic_cast<T>(u); }

struct cast_selector<true>
   template <class T, class U>
   static T do_cast(U u, T) { return static_cast<T>(u); }

} // detail

template <class T, class U>
T maybe_cast(U* u, T = 0)
   typedef detail::cast_selector<is_convertible<U*,T>::value> sw;
   return sw::do_cast(u, (T)(0));

By using something like this internally in shared_ptr, the range of
available convertions for polymorphic types would be greatly extended,
without changing existing behaviour as far as I know. The down side is an
increase in complexity of the curently simple shared_ptr template.


- John.

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