Boost :: any and polymorphism

I use boost::any to store pointers and wonder if there is a way to extract a polymorphic data type.

Here is a simple example of what, ideally, I would like to do, but is currently not working.

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

This fails because a stores B *, and I'm trying to extract A *. Is there any way to do this?

Thanks.

+4
source share
3 answers

Another way is to save A* in boost::any , and then dynamic_cast output. Sort of:

 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; } 
+4
source

Boost.DynamicAny is a vairant on Boost.Any that provides a more flexible dynamic casting of the base type. While getting a value from Boost.Any requires you to know the exact type stored in Any, Boost.DynamicAny allows you to dynamically enter either a base or a derived class of a held type.

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

+7
source

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

 static_cast<A*>(boost::any_cast<B*>(a)) 
+3
source

All Articles