views:

277

answers:

2

I am using boost::any to store pointers and was wondering if there was a way to extract a polymorphic data type.

Here is a simple example of what ideally I'd like to do, but currently doesn't work.

struct A {};

struct B : A {};

int main() {

    boost::any a;
    a = new B();
    boost::any_cast< A* >(a);
}

This fails because a is storing a B*, and I'm trying to extract an A*. Is there a way to accomplish this?

Thanks.

+3  A: 

Unfortunately, I think the only way to do it is this:

static_cast<A*>(boost::any_cast<B*>(a))
Zifre
+1  A: 

The other way is to store an A* in the boost::any and then dynamic_cast the output. Something like:

int main() {
    boost::any a = (A*)new A;
    boost::any b = (A*)new B;
    A *anObj = boost::any_cast<A*>(a);
    B *anotherObj = dynamic_cast<B*>(anObj); // <- this is NULL

    anObj = boost::any_cast<A*>(b);
    anotherObj = dynamic_cast<B*>(anObj); // <- this one works!

    return 0;
}
D.Shawley
Zifre is right, static_cast is more appropriate here.
the_drow