polymorphic_pointer_cast.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // boost polymorphic_pointer_cast.hpp header file ----------------------------------------------//
  2. // (C) Copyright Boris Rasin, 2014-2021.
  3. // (C) Copyright Antony Polukhin, 2014-2024.
  4. // Distributed under the Boost
  5. // Software License, Version 1.0. (See accompanying file
  6. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. // See http://www.boost.org/libs/conversion for Documentation.
  8. #ifndef BOOST_CONVERSION_POLYMORPHIC_POINTER_CAST_HPP
  9. #define BOOST_CONVERSION_POLYMORPHIC_POINTER_CAST_HPP
  10. #include <boost/config.hpp>
  11. #ifdef BOOST_HAS_PRAGMA_ONCE
  12. # pragma once
  13. #endif
  14. # include <boost/assert.hpp>
  15. # include <boost/pointer_cast.hpp>
  16. # include <boost/throw_exception.hpp>
  17. namespace boost
  18. {
  19. // See the documentation for descriptions of how to choose between
  20. // static_pointer_cast<>, dynamic_pointer_cast<>, polymorphic_pointer_cast<> and polymorphic_pointer_downcast<>
  21. // polymorphic_pointer_downcast --------------------------------------------//
  22. // BOOST_ASSERT() checked polymorphic downcast. Crosscasts prohibited.
  23. // Supports any type with static_pointer_cast/dynamic_pointer_cast functions:
  24. // built-in pointers, std::shared_ptr, boost::shared_ptr, boost::intrusive_ptr, etc.
  25. // WARNING: Because this cast uses BOOST_ASSERT(), it violates
  26. // the One Definition Rule if used in multiple translation units
  27. // where BOOST_DISABLE_ASSERTS, BOOST_ENABLE_ASSERT_HANDLER
  28. // NDEBUG are defined inconsistently.
  29. // Contributed by Boris Rasin
  30. template <typename Target, typename Source>
  31. inline auto polymorphic_pointer_downcast (const Source& x)
  32. -> decltype(static_pointer_cast<Target>(x))
  33. {
  34. BOOST_ASSERT(dynamic_pointer_cast<Target> (x) == x);
  35. return static_pointer_cast<Target> (x);
  36. }
  37. template <typename Target, typename Source>
  38. inline auto polymorphic_pointer_cast (const Source& x)
  39. -> decltype(dynamic_pointer_cast<Target>(x))
  40. {
  41. auto tmp = dynamic_pointer_cast<Target> (x);
  42. if ( !tmp ) boost::throw_exception( std::bad_cast() );
  43. return tmp;
  44. }
  45. } // namespace boost
  46. #endif // BOOST_CONVERSION_POLYMORPHIC_POINTER_CAST_HPP