How to use boost :: any_cast (C ++ library) for use in basic types?

I use boost :: any to have polymorphic types, I need the object to be bound to its base type.

class A { public: int x; virtual int foo()= 0; }; class B : public A { public: int foo() { return x + 1; } }; int main() { B* bb = new B(); boost::any any = bb; bb->x = 44; A* aa = boost::any_cast<A*>(any); } 

The main function code throws the following error at runtime:

 terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_any_cast> >' what(): boost::bad_any_cast: failed conversion using boost::any_cast Abort trap 

If I change static_cast in boost :: any_cast code for reinterpret_cast, this will work. However, I am not sure about the consequences of this.

Do you have any ideas?

+4
source share
1 answer

Upcasts (to pointer-to-base) does not require explicit casts in C ++.

On the other hand, boost::any_cast will succeed only when casting to the same type that was originally saved. (IIRC uses typeid to verify that you are trying to access the correct type, and type mappings are used only for exact matches.)

Hence:

 A* aa = boost::any_cast<B*>(any); 

However, it is somewhat unclear why you should use boost::any for polymorphic types. In particular, it is not a smart pointer and will not delete a stored object. More common is storing pointers to a polymorphic object in a smart pointer, for example boost::shared_ptr<A>

+7
source

All Articles