cast_test.cpp 2.4 KB

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