Boost logo

Boost :

Subject: Re: [boost] [DynamicAny] Feedback
From: Alexander Nasonov (alnsn_at_[hidden])
Date: 2011-03-05 06:13:08


Daniel Larimer wrote:
> I recently ran into a problem where I wanted to retrieve the value stored in a boost::any by casting to a base class. Unfortunately, boost::any requires you cast out the exact type as that held.
> Boost.DynamicAny is a vairant on Boost.Any which provides more flexible dynamic casting of the underlying type. Whereas retreiving a value from Boost.Any requires that you know the exact type stored within the Any, Boost.DynamicAny allows you to dynamically cast to either a base or derived class of the held type.

I don't see how you can cast to "derived class of the held type" because
holder<T> always stores a (sliced) copy of an object you passed to a
constructor. Your test casts either to base classes or to the same type.

We discussed this feature several years ago but for some reason I didn't
commit it.

Take a look at this:

http://cpp-experiment.cvs.sourceforge.net/viewvc/cpp-experiment/dynamic_any/boost/dynamic_any/any.hpp?revision=1.49&view=markup

Alex

> Boost.DynamicAny is a vairant on Boost.Any which provides more flexible dynamic casting of the underlying type. Whereas retreiving a value from Boost.Any requires that you know the exact type stored within the Any, Boost.DynamicAny allows you to dynamically cast to either a base or derived class of the held type.
> Boost.DynamicAny passes all of the same unit tests as Boost.Any, but additionally supports the following test:
>
> #include <boost/dynamic_any.hpp>
>
> using boost::dynamic_any_cast;
> struct base
> {
> int a;
> };
>
> struct base1
> {
> int a1;
> };
>
> struct derived : base, base1
> {
> int b;
> };
>
> struct other {};
>
> void test_dynamic_cast()
> {
> derived d;
> dynamic_any a(d);
> derived & ra = dynamic_any_cast<derived&>(a);
> base & b = dynamic_any_cast<base&>(a);
> base1 & b1 = dynamic_any_cast<base1&>(a);
> const base1 & cb1 = dynamic_any_cast<const base1&>(a);
>
> TEST_CHECK_THROW(
> dynamic_any_cast<other&>(a),
> bad_dynamic_any_cast,
> "dynamic_any_cast to incorrect reference type");
>
> For scalar types, Boost.DynamicAny works just like Boost.Any. This means that it currently does not support dynamic casting of pointers stored within the any, but that should not be too hard to add.
>
> https://github.com/bytemaster/Boost.DynamicAny
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
>

-- 

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