diff --git a/src/templates/smartp.hh b/src/templates/smartp.hh index 04111b6..9f249ff 100644 --- a/src/templates/smartp.hh +++ b/src/templates/smartp.hh @@ -18,15 +18,17 @@ #define SMARTP_HH 1 #include +#include namespace memory { /** \brief A simple reference counted smart pointer * * \author Matteo Settenvini - * \version 1.0 - * \date October 2005 - * + * + * \version \c 1.1, March 7th, 2006 - Add support for dynamic casting + * \version \c 1.0, October 10th, 2006 - Initial stable release + * * This template is a smart pointer which uses * a simple mechanism of reference count to * keep track of when and if a stored object @@ -115,6 +117,35 @@ namespace memory { * \return The number of references */ inline unsigned int alive_refs() const throw(); + + /** \brief Dynamic cast the stored pointer + * to another type + * + * This functions tries to cast the stored + * object to the given type. + * + * \param U The type to cast to. + * \return A reference of the casted type + * \exception bad_alloc Raise this exception if + * the cast isn't successful. + */ + template + inline U& cast_to() throw(std::bad_cast); + + /** \brief Dynamic cast the stored pointer + * to another type + * + * This functions tries to cast the stored + * object to the given type. + * + * \param U The type to cast to. + * \return A const reference of the casted type + * \exception bad_alloc Raise this exception if + * the cast isn't successful. + */ + template + inline const U& cast_to() const throw(std::bad_cast); + private: struct contents_type { T* ptr; diff --git a/src/templates/smartp.tcc b/src/templates/smartp.tcc index 26922cc..1e10500 100644 --- a/src/templates/smartp.tcc +++ b/src/templates/smartp.tcc @@ -140,6 +140,30 @@ namespace memory { return _contents->ptr != 0 ? _contents->rc : 0; } + + template + template + U& + smart_ptr::cast_to() throw(std::bad_cast) + { + if(_contents->ptr != 0) + return dynamic_cast(*_contents->ptr); + else + throw std::bad_cast(); + } + + + template + template + const U& + smart_ptr::cast_to() const throw(std::bad_cast) + { + if(_contents->ptr != 0) + return dynamic_cast(*_contents->ptr); + else + throw std::bad_cast(); + } + } //~ namespace memory #endif