std_shared_ptr_cast.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. #ifndef BOOST_TYPE_INDEX_RUNTIME_CAST_STD_SHARED_PTR_CAST_HPP
  9. #define BOOST_TYPE_INDEX_RUNTIME_CAST_STD_SHARED_PTR_CAST_HPP
  10. /// \file std_shared_ptr_cast.hpp
  11. /// \brief Contains the overload of boost::typeindex::runtime_pointer_cast for
  12. /// std::shared_ptr types.
  13. #include <boost/type_index/runtime_cast/detail/runtime_cast_impl.hpp>
  14. #include <boost/type_traits/is_base_and_derived.hpp>
  15. #include <memory>
  16. #ifdef BOOST_HAS_PRAGMA_ONCE
  17. # pragma once
  18. #endif
  19. namespace boost { namespace typeindex {
  20. /// \brief Creates a new instance of std::shared_ptr whose stored pointer is obtained from u's
  21. /// stored pointer using a runtime_cast.
  22. ///
  23. /// The new shared_ptr will share ownership with u, except that it is empty if the runtime_cast
  24. /// performed by runtime_pointer_cast returns a null pointer.
  25. /// \tparam T The desired target type to return a pointer of.
  26. /// \tparam U A complete class type of the source instance pointed to from u.
  27. /// \return If there exists a valid conversion from U* to T*, returns a std::shared_ptr<T>
  28. /// that points to an address suitably offset from u.
  29. /// If no such conversion exists, returns std::shared_ptr<T>();
  30. template<typename T, typename U>
  31. std::shared_ptr<T> runtime_pointer_cast(std::shared_ptr<U> const& u) {
  32. T* value = detail::runtime_cast_impl<T>(u.get(), boost::is_base_and_derived<T, U>());
  33. if(value)
  34. return std::shared_ptr<T>(u, value);
  35. return std::shared_ptr<T>();
  36. }
  37. }} // namespace boost::typeindex
  38. #endif // BOOST_TYPE_INDEX_RUNTIME_CAST_STD_SHARED_PTR_CAST_HPP