Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost::any and polymorphism

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.

like image 878
Kranar Avatar asked Dec 09 '22 20:12

Kranar


1 Answers

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.

https://github.com/bytemaster/Boost.DynamicAny

like image 133
Daniel Larimer Avatar answered Dec 24 '22 11:12

Daniel Larimer