Boost logo

Boost :

Subject: Re: [boost] [type_index] Interest in dynamic_cast emulation?
From: Chris Glover (c.d.glover_at_[hidden])
Date: 2016-07-15 17:53:13


Hi,

I have placed an initial implementation here:

https://github.com/cdglove/type_index/tree/runtime_cast

Here's the commit:

https://github.com/cdglove/type_index/commit/ee7b15a493d10bc1fad93a12ab42f2fdfd260810

Usage:

1. #include <boost/type_index/runtime_cast.hpp>
2. Add a macro to your classes to opt in;

struct base {
    BOOST_TYPE_INDEX_REGISTER_CLASS_RTTI
};

3. Derived classes need to list bases

struct multiple_derived : base1, base2 {
    BOOST_TYPE_INDEX_REGISTER_CLASS_RTTI_BASES(base1, base2)
};

4. use boost::type_index::runtime_cast the same as dynamic_cast,
(boost::type_index::runtime_pointer_cast like other boost::*pointer casts.).

Example:

using namespace boost::typeindex;
multiple_derived d;
base1* b1 = &d;
multiple_derived* d2 = runtime_pointer_cast<multiple_derived>(b1);
BOOST_TEST_NE(d2, (multiple_derived*)nullptr);
base2* b2 = runtime_pointer_cast<base2>(b1);
BOOST_TEST_NE(b2, (base2*)nullptr);

Some notes about the implementation:

1. I am using a variadic template. This could be removed if backwards
compatibility is desired.
2. The error messages could use some work.
3. I'm not sure if the tests are comprehensive, does anyone see anything
I've missed? I believe I have considered all combinations of multiple and
virtual inheritance that could mess this up.
4. It's possible this doesn't belong in the type_index library.
5. Initial performance tests put this about 5x slower than dynamic cast.
But those tests are trivial so I need to construct something more complex
to get an accurate measure of real world performance.

Any feedback is welcome.

Thanks,

-- chris


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk