2 // Test boost::polymorphic_cast, boost::polymorphic_downcast
4 // Copyright 1999 Beman Dawes
5 // Copyright 1999 Dave Abrahams
6 // Copyright 2014 Peter Dimov
8 // Distributed under the Boost Software License, Version 1.0.
10 // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
13 #define BOOST_ENABLE_ASSERT_HANDLER
14 #include <boost/polymorphic_cast.hpp>
15 #include <boost/core/lightweight_test.hpp>
18 static bool expect_assertion = false;
19 static int assertion_failed_count = 0;
21 // BOOST_ASSERT custom handler
22 void boost::assertion_failed( char const * expr, char const * function, char const * file, long line )
24 if( expect_assertion )
26 ++assertion_failed_count;
30 BOOST_ERROR( "unexpected assertion" );
32 BOOST_LIGHTWEIGHT_TEST_OSTREAM
33 << file << "(" << line << "): assertion '" << expr << "' failed in function '"
34 << function << "'" << std::endl;
43 virtual std::string kind() { return "Base"; }
49 virtual std::string kind2() { return "Base2"; }
52 struct Derived : public Base, Base2
54 virtual std::string kind() { return "Derived"; }
57 static void test_polymorphic_cast()
59 Base * base = new Derived;
65 derived = boost::polymorphic_cast<Derived*>( base );
67 BOOST_TEST( derived != 0 );
71 BOOST_TEST_EQ( derived->kind(), "Derived" );
74 catch( std::bad_cast const& )
76 BOOST_ERROR( "boost::polymorphic_cast<Derived*>( base ) threw std::bad_cast" );
83 base2 = boost::polymorphic_cast<Base2*>( base ); // crosscast
85 BOOST_TEST( base2 != 0 );
89 BOOST_TEST_EQ( base2->kind2(), "Base2" );
92 catch( std::bad_cast const& )
94 BOOST_ERROR( "boost::polymorphic_cast<Base2*>( base ) threw std::bad_cast" );
100 static void test_polymorphic_downcast()
102 Base * base = new Derived;
104 Derived * derived = boost::polymorphic_downcast<Derived*>( base );
106 BOOST_TEST( derived != 0 );
110 BOOST_TEST_EQ( derived->kind(), "Derived" );
113 // polymorphic_downcast can't do crosscasts
118 static void test_polymorphic_cast_fail()
120 Base * base = new Base;
122 BOOST_TEST_THROWS( boost::polymorphic_cast<Derived*>( base ), std::bad_cast );
127 static void test_polymorphic_downcast_fail()
129 Base * base = new Base;
131 int old_count = assertion_failed_count;
132 expect_assertion = true;
134 boost::polymorphic_downcast<Derived*>( base ); // should assert
136 BOOST_TEST_EQ( assertion_failed_count, old_count + 1 );
137 expect_assertion = false;
144 test_polymorphic_cast();
145 test_polymorphic_downcast();
146 test_polymorphic_cast_fail();
147 test_polymorphic_downcast_fail();
149 return boost::report_errors();