Boost logo

Boost :

Subject: [boost] [DynamicAny] Feedback
From: Daniel Larimer (dlarimer_at_[hidden])
Date: 2011-03-03 23:58:30


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.
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


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