/* The software in this package is distributed under the GNU General Public License version 2 (with a special exception described below). A copy of GNU General Public License (GPL) is included in this distribution, in the file COPYING.GPL. As a special exception, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other works to produce a work based on this file, this file does not by itself cause the resulting work to be covered by the GNU General Public License. However the source code for this file must still be made available in accordance with section (3) of the GNU General Public License. This exception does not invalidate any other reasons why a work based on this file might be covered by the GNU General Public License. */ /** @file * @brief provides a little base class for classes wich are used in conjunction with shared pointer. * * @author Reinhard Pfau * * @copyright © Copyright 2008 Intra2Net AG * */ #ifndef __I2N_POINTER_FUNC_HPP__ #define __I2N_POINTER_FUNC_HPP__ #include #include namespace I2n { /** * @brief base class for classes used as type with shared pointers. * * Must be virtually inherited by (base) classes which are used in * conjunction with shared pointers. * * Allows these classes (and its derived classes) to protect their methods * against preliminary deletion by giving them the possibility to obtain * a shared pointer to themself. */ class SharedBase : public boost::enable_shared_from_this< SharedBase > { public: typedef boost::shared_ptr< SharedBase > BasePtrType; typedef boost::shared_ptr< SharedBase > PtrType; public: SharedBase(); virtual ~SharedBase(); /** * @brief gets a shared pointer to itself if applicable. * @return the shared pointer (to the base class); empty if not applicable. * * The method catches the @a boost::bad_weak_ptr exception and ignores it. * So this method doesn't throw if the instance is not held by a shared pointer. */ BasePtrType get_base_ptr() { BasePtrType result; try { result = shared_from_this(); } catch (boost::bad_weak_ptr) { } return result; } // eo get_base_ptr /** * @brief gets a shared pointer to itself with a specific (derived) type. * @tparam T the desired type for the shared pointer. * @return the shared pointer (to the desired type); empty if not applicable. * * The method catches the @a boost::bad_weak_ptr exception and ignores it. * So this method doesn't throw if the instance is not held by a shared pointer. */ template< class T > boost::shared_ptr< T > get_ptr_as() { boost::shared_ptr< T > result; BasePtrType ptr; try { ptr = shared_from_this(); } catch (boost::bad_weak_ptr) { } if (ptr) { result= boost::dynamic_pointer_cast< T >(ptr); } return result; } // eo get_ptr_as }; // eo SharedBase typedef SharedBase::PtrType SharedBasePtr; } // eo namespace I2n #endif