inheritance.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2013-2019 Antony Polukhin
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See the accompanying file LICENSE_1_0.txt
  4. // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
  5. //[type_index_derived_example
  6. /*`
  7. The following example shows that `type_info` is able to store the real type, successfully getting through
  8. all the inheritances.
  9. Example works with and without RTTI."
  10. */
  11. #include <boost/type_index.hpp>
  12. #include <boost/type_index/runtime_cast/register_runtime_class.hpp>
  13. #include <iostream>
  14. struct A {
  15. BOOST_TYPE_INDEX_REGISTER_CLASS
  16. virtual ~A(){}
  17. };
  18. struct B: public A { BOOST_TYPE_INDEX_REGISTER_CLASS };
  19. struct C: public B { BOOST_TYPE_INDEX_REGISTER_CLASS };
  20. struct D: public C { BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS(BOOST_TYPE_INDEX_NO_BASE_CLASS) };
  21. void print_real_type(const A& a) {
  22. std::cout << boost::typeindex::type_id_runtime(a).pretty_name() << '\n';
  23. }
  24. int main() {
  25. C c;
  26. const A& c_as_a = c;
  27. print_real_type(c_as_a); // Outputs `struct C`
  28. print_real_type(B()); // Outputs `struct B`
  29. /*`
  30. It's also possible to use type_id_runtime with the BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS, which adds additional
  31. information for runtime_cast to work.
  32. */
  33. D d;
  34. const A& d_as_a = d;
  35. print_real_type(d_as_a); // Outputs `struct D`
  36. }
  37. //] [/type_index_derived_example]