1 // boost utility cast test program -----------------------------------------// 2 3 // (C) Copyright Beman Dawes, Dave Abrahams 1999. Distributed under the Boost 4 // Software License, Version 1.0. (See accompanying file 5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6 7 // See http://www.boost.org for most recent version including documentation. 8 9 // Revision History 10 // 28 Set 04 factored out numeric_cast<> test (Fernando Cacciola) 11 // 20 Jan 01 removed use of <limits> for portability to raw GCC (David Abrahams) 12 // 28 Jun 00 implicit_cast removed (Beman Dawes) 13 // 30 Aug 99 value_cast replaced by numeric_cast 14 // 3 Aug 99 Initial Version 15 16 #include <iostream> 17 #include <boost/polymorphic_cast.hpp> 18 #include <boost/core/lightweight_test.hpp> 19 20 using namespace boost; 21 using std::cout; 22 23 namespace 24 { 25 struct Base 26 { kind__anon127e0f120111::Base27 virtual char kind() { return 'B'; } 28 }; 29 30 struct Base2 31 { kind2__anon127e0f120111::Base232 virtual char kind2() { return '2'; } 33 }; 34 35 struct Derived : public Base, Base2 36 { kind__anon127e0f120111::Derived37 virtual char kind() { return 'D'; } 38 }; 39 } 40 41 main(int argc,char * argv[])42int main( int argc, char * argv[] ) 43 { 44 # ifdef NDEBUG 45 cout << "NDEBUG is defined\n"; 46 # else 47 cout << "NDEBUG is not defined\n"; 48 # endif 49 50 cout << "\nBeginning tests...\n"; 51 52 // test polymorphic_cast ---------------------------------------------------// 53 54 // tests which should succeed 55 Derived derived_instance; 56 Base * base = &derived_instance; 57 Derived * derived = polymorphic_downcast<Derived*>( base ); // downcast 58 BOOST_TEST( derived->kind() == 'D' ); 59 60 derived = polymorphic_cast<Derived*>( base ); // downcast, throw on error 61 BOOST_TEST( derived->kind() == 'D' ); 62 63 Base2 * base2 = polymorphic_cast<Base2*>( base ); // crosscast 64 BOOST_TEST( base2->kind2() == '2' ); 65 66 // tests which should result in errors being detected 67 Base base_instance; 68 base = &base_instance; 69 70 if ( argc > 1 && *argv[1] == '1' ) 71 { derived = polymorphic_downcast<Derived*>( base ); } // #1 assert failure 72 73 bool caught_exception = false; 74 try { derived = polymorphic_cast<Derived*>( base ); } 75 catch (const std::bad_cast&) 76 { cout<<"caught bad_cast\n"; caught_exception = true; } 77 BOOST_TEST( caught_exception ); 78 // the following is just so generated code can be inspected 79 BOOST_TEST( derived->kind() != 'B' ); 80 81 return boost::report_errors(); 82 } // main 83