| 1 | // |
| 2 | // Copyright (c) Chris Glover, 2016. |
| 3 | // |
| 4 | // |
| 5 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 6 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 7 | // |
| 8 | |
| 9 | #ifndef BOOST_TYPE_INDEX_RUNTIME_CAST_STD_SHARED_PTR_CAST_HPP |
| 10 | #define BOOST_TYPE_INDEX_RUNTIME_CAST_STD_SHARED_PTR_CAST_HPP |
| 11 | |
| 12 | /// \file std_shared_ptr_cast.hpp |
| 13 | /// \brief Contains the overload of boost::typeindex::runtime_pointer_cast for |
| 14 | /// std::shared_ptr types. |
| 15 | |
| 16 | #include <boost/type_index/runtime_cast/detail/runtime_cast_impl.hpp> |
| 17 | #include <memory> |
| 18 | |
| 19 | #ifdef BOOST_HAS_PRAGMA_ONCE |
| 20 | # pragma once |
| 21 | #endif |
| 22 | |
| 23 | namespace boost { namespace typeindex { |
| 24 | |
| 25 | /// \brief Creates a new instance of std::shared_ptr whose stored pointer is obtained from u's |
| 26 | /// stored pointer using a runtime_cast. |
| 27 | /// |
| 28 | /// The new shared_ptr will share ownership with u, except that it is empty if the runtime_cast |
| 29 | /// performed by runtime_pointer_cast returns a null pointer. |
| 30 | /// \tparam T The desired target type to return a pointer of. |
| 31 | /// \tparam U A complete class type of the source instance pointed to from u. |
| 32 | /// \return If there exists a valid conversion from U* to T*, returns a std::shared_ptr<T> |
| 33 | /// that points to an address suitably offset from u. |
| 34 | /// If no such conversion exists, returns std::shared_ptr<T>(); |
| 35 | template<typename T, typename U> |
| 36 | std::shared_ptr<T> runtime_pointer_cast(std::shared_ptr<U> const& u) { |
| 37 | T* value = detail::runtime_cast_impl<T>(u.get(), std::is_base_of<T, U>()); |
| 38 | if(value) |
| 39 | return std::shared_ptr<T>(u, value); |
| 40 | return std::shared_ptr<T>(); |
| 41 | } |
| 42 | |
| 43 | }} // namespace boost::typeindex |
| 44 | |
| 45 | #endif // BOOST_TYPE_INDEX_RUNTIME_CAST_STD_SHARED_PTR_CAST_HPP |
| 46 | |