Initial documentation.

This commit is contained in:
Chris Glover
2016-08-11 10:31:16 -04:00
parent 5af925602e
commit ad26256d09
11 changed files with 211 additions and 23 deletions

View File

@ -21,6 +21,7 @@ struct A {
};
struct B: public A { BOOST_TYPE_INDEX_REGISTER_CLASS };
struct C: public B { BOOST_TYPE_INDEX_REGISTER_CLASS };
struct D: public C { BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS(BOOST_TYPE_INDEX_NO_BASE_CLASS) };
void print_real_type(const A& a) {
std::cout << boost::typeindex::type_id_runtime(a).pretty_name() << '\n';
@ -31,6 +32,15 @@ int main() {
const A& c_as_a = c;
print_real_type(c_as_a); // Outputs `struct C`
print_real_type(B()); // Outputs `struct B`
/*`
It's also possible to use type_id_runtime with the BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS, which adds additional
information for runtime_cast to work.
*/
D c;
const A& d_as_a = d;
print_real_type(dc_as_a); // Outputs `struct D`
}
//] [/type_index_derived_example]

78
examples/runtime_cast.cpp Normal file
View File

@ -0,0 +1,78 @@
//
// Copyright (c) Chris Glover, 2016.
//
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//[type_index_runtime_cast_example
/*`
The following example shows that `runtime_cast` is able to find a valid pointer
in various class hierarchies regardless of inheritance or type relation.
Example works with and without RTTI."
*/
#include <boost/type_index/runtime_cast.hpp>
#include <iostream>
struct A {
BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS(BOOST_TYPE_INDEX_NO_BASE_CLASS)
virtual ~A()
{}
};
struct B {
BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS(BOOST_TYPE_INDEX_NO_BASE_CLASS)
virtual ~B()
{}
};
struct C : A {
BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS((A))
};
struct D : B {
BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS((B))
};
struct E : C, D {
BOOST_TYPE_INDEX_REGISTER_RUNTIME_CLASS((C)(D))
};
int main() {
C c;
A* a = &c;
if(C* cp = boost::typeindex::runtime_cast<C*>(a))
std::cout << "Yes, a points to a C." << '\n';
else
std::cout << "Error: Expected a to point to a C" << '\n';
if(E* ce = boost::typeindex::runtime_cast<E*>(a))
std::cout << "Error: Expected a to not points to an E." << '\n';
else
std::cout << "But, a does not point to an E" << '\n';
E e;
C* cp = &e;
if(D* dp = boost::typeindex::runtime_cast<D*>(cp))
std::cout << "Yes, we can cross-cast from a C* to a D* when we actually have an E." << '\n';
else
std::cout << "Error: Expected cp to point to a D" << '\n';
/*`
Alternatively, we can use runtime_pointer_cast so we don't need to specity the target as a pointer.
This works for smart_ptr types too.
*/
A* ap = &e;
if(B* bp = boost::typeindex::runtime_pointer_cast<B>(ap))
std::cout << "Yes, we can cross-cast and up-cast at the same time." << '\n';
else
std::cout << "Error: Expected ap to point to a B" << '\n';
return 0;
}
//] [/type_index_runtime_cast_example]