=add polymorphic_pointer_downcast function template

This commit is contained in:
Boris Rasin
2014-11-09 00:02:44 +02:00
parent 5d66fea7d5
commit 6a224fa5e9
4 changed files with 99 additions and 9 deletions
+40
View File
@@ -1,6 +1,7 @@
// boost polymorphic_cast.hpp header file ----------------------------------------------//
// (C) Copyright Kevlin Henney and Dave Abrahams 1999.
// (C) Copyright Boris Rasin 2014.
// Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
@@ -8,6 +9,7 @@
// See http://www.boost.org/libs/conversion for Documentation.
// Revision History
// 08 Nov 14 Add polymorphic_pointer_downcast (Boris Rasin)
// 09 Jun 14 "cast.hpp" was renamed to "polymorphic_cast.hpp" and
// inclusion of numeric_cast was removed (Antony Polukhin)
// 23 Jun 05 numeric_cast removed and redirected to the new verion (Fernando Cacciola)
@@ -47,6 +49,9 @@
# include <boost/config.hpp>
# include <boost/assert.hpp>
# include <boost/pointer_cast.hpp>
# include <boost/utility/declval.hpp>
# include <boost/typeof/typeof.hpp>
# include <typeinfo>
namespace boost
@@ -86,6 +91,41 @@ namespace boost
return static_cast<Target>(x);
}
// polymorphic_pointer_downcast --------------------------------------------//
// BOOST_ASSERT() checked polymorphic downcast. Crosscasts prohibited.
// Supports any type with static_pointer_cast/dynamic_pointer_cast functions:
// built-in pointers, std::shared_ptr, boost::shared_ptr, boost::intrusive_ptr, etc.
// WARNING: Because this cast uses BOOST_ASSERT(), it violates
// the One Definition Rule if used in multiple translation units
// where BOOST_DISABLE_ASSERTS, BOOST_ENABLE_ASSERT_HANDLER
// NDEBUG are defined inconsistently.
// Contributed by Boris Rasin
namespace detail
{
template <typename Target, typename Source>
struct static_pointer_cast_result
{
#ifdef BOOST_NO_CXX11_DECLTYPE
BOOST_TYPEOF_NESTED_TYPEDEF_TPL(nested, static_pointer_cast<Target>(boost::declval<Source>()))
typedef typename nested::type type;
#else
typedef decltype(static_pointer_cast<Target>(boost::declval<Source>())) type;
#endif
};
}
template <typename Target, typename Source>
inline typename detail::static_pointer_cast_result<Target, Source>::type
polymorphic_pointer_downcast (const Source& x)
{
BOOST_ASSERT(dynamic_pointer_cast<Target> (x) == x);
return static_pointer_cast<Target> (x);
}
} // namespace boost
#endif // BOOST_POLYMORPHIC_CAST_HPP