Brian Silverman | 87d3c95 | 2018-08-05 00:08:45 -0700 | [diff] [blame^] | 1 | // |
| 2 | // Copyright (c) Chris Glover, 2016. |
| 3 | // |
| 4 | // |
| 5 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 6 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 7 | // |
| 8 | |
| 9 | //[type_index_runtime_cast_example |
| 10 | /*` |
| 11 | The following example shows that `runtime_cast` is able to find a valid pointer |
| 12 | in various class hierarchies regardless of inheritance or type relation. |
| 13 | |
| 14 | Example works with and without RTTI." |
| 15 | */ |
| 16 | |
| 17 | #include <boost/type_index/runtime_cast.hpp> |
| 18 | #include <iostream> |
| 19 | |
| 20 | struct A { |
| 21 | BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS(BOOST_TYPE_INDEX_NO_BASE_CLASS) |
| 22 | virtual ~A() |
| 23 | {} |
| 24 | }; |
| 25 | |
| 26 | struct B { |
| 27 | BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS(BOOST_TYPE_INDEX_NO_BASE_CLASS) |
| 28 | virtual ~B() |
| 29 | {} |
| 30 | }; |
| 31 | |
| 32 | struct C : A { |
| 33 | BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS((A)) |
| 34 | }; |
| 35 | |
| 36 | struct D : B { |
| 37 | BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS((B)) |
| 38 | }; |
| 39 | |
| 40 | struct E : C, D { |
| 41 | BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS((C)(D)) |
| 42 | }; |
| 43 | |
| 44 | int main() { |
| 45 | C c; |
| 46 | A* a = &c; |
| 47 | |
| 48 | if(C* cp = boost::typeindex::runtime_cast<C*>(a)) { |
| 49 | std::cout << "Yes, a points to a C: " |
| 50 | << a << "->" << cp << '\n'; |
| 51 | } |
| 52 | else { |
| 53 | std::cout << "Error: Expected a to point to a C" << '\n'; |
| 54 | } |
| 55 | |
| 56 | if(E* ce = boost::typeindex::runtime_cast<E*>(a)) { |
| 57 | std::cout << "Error: Expected a to not points to an E: " |
| 58 | << a << "->" << ce << '\n'; |
| 59 | } |
| 60 | else { |
| 61 | std::cout << "But, a does not point to an E" << '\n'; |
| 62 | } |
| 63 | |
| 64 | E e; |
| 65 | C* cp2 = &e; |
| 66 | if(D* dp = boost::typeindex::runtime_cast<D*>(cp2)) { |
| 67 | std::cout << "Yes, we can cross-cast from a C* to a D* when we actually have an E: " |
| 68 | << cp2 << "->" << dp << '\n'; |
| 69 | } |
| 70 | else { |
| 71 | std::cout << "Error: Expected cp to point to a D" << '\n'; |
| 72 | } |
| 73 | |
| 74 | /*` |
| 75 | Alternatively, we can use runtime_pointer_cast so we don't need to specity the target as a pointer. |
| 76 | This works for smart_ptr types too. |
| 77 | */ |
| 78 | A* ap = &e; |
| 79 | if(B* bp = boost::typeindex::runtime_pointer_cast<B>(ap)) { |
| 80 | std::cout << "Yes, we can cross-cast and up-cast at the same time." |
| 81 | << ap << "->" << bp << '\n'; |
| 82 | } |
| 83 | else { |
| 84 | std::cout << "Error: Expected ap to point to a B" << '\n'; |
| 85 | } |
| 86 | |
| 87 | return 0; |
| 88 | } |
| 89 | |
| 90 | //] [/type_index_runtime_cast_example] |