Boost logo

Boost :

Subject: Re: [boost] [type_erasure] any_cast to a base class?
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2014-03-12 12:43:42


AMDG

On 03/12/2014 04:22 AM, Phil Endecott wrote:
> Dear Experts,
>
> Can boost::type_erasure::any_cast cast to a base class? For example:
>
> class Base {};
> class Derived: public Base {};
> Derived d;
> any< ??? > a (d);
> Base* b = any_cast<Base*>(&a);
> assert(b);
>
> I know that this isn't possible with Boost.Any, but was hoping that
> Boost.TypeErasure would include some "magic" to make it possible.
> Failing that, are there any other options?
>

There is some possible magic involving dynamic_cast
internally, but it's a bit unreliable. I decided
that it wasn't worth it for Boost.TypeErasure.
(Look up Boost.DynamicAny, which Alexander Nasonov
proposed a while back.)

> (What I'd really like to do is to store a weak_ptr<Derived> and
> retrieve a shared_ptr<Base>, and other similar combinations, but
> I get stuck before I get that far.)
>

These are completely unrelated types.
I don't see how I could make it work in general.
I suppose that it would be possible with some help:

convertible_to<weak_ptr<void> > // Hypothetical concept

// Sets up some kind of global table
template<class Base, class Derived>
void register_base_derived();

// Looks up the cast and runs it (Note that this
// is basically equivalent to the internals of
// dynamic_cast which can't be accessed portably)
void * upcast(
    const std::type_info& src_type,
    const std::type_info& dst_type, void * src);

any<...> x = weak_ptr<Derived>(...);
weak_ptr<void> wptr(x);
shared_ptr<void> sptr(wptr.lock());
// use upcast to get a Base* then construct
// a shared_ptr<Base> that shares ownership
// with sptr.

In Christ,
Steven Watanabe


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