Boost logo

Boost Users :

From: Rene Rivera (grafik.list_at_[hidden])
Date: 2006-02-08 10:41:57


Iulian M wrote:
> Hello,
>
> I'm trying to use boost::any to store a group of types. For value types
> everything works as expected. The problem is that i need to store some
> polymorphic types also. The following code explains what i'm trying to
> accomplish.
>
> #include <boost/any.hpp>
>
> class A {}; //base calss
> class B: public A {}; // derived class
>
> int main()
> {
> B *b = new B(); //create derived class
> boost::any n(b); // place inside boost::any
>
> /*
> other part of code where i only know n contains a pointer to a class
> derived from A
> this will throw bad_any_cast: typeid(A*) != typeid (B*)
> */
> A* a = boost::any_cast<A*>(n);
> }
>
> Is there any way of making boost::any_cast work work ok with "convertible"
> types? Or is there a way of storing different types of objects and having the
> possibility of retrieving them as compatible objects ?
>
> I've looked into any.hpp and found that it uses a typeid() equality test to
> see if the cast can be made. Can't there be a is_convertible test insted , at
> least for the case when is holding pointer to objects?

There's no easy way for the boost.any code to work with polymorphic
types as you expect since there's no current way to know what types are
convertible at runtime. (Perhaps when there's a boost.reflect)

There's an easy workaround though, which is the same as you and the
compiler would use if you had, for example, a "A* v". You can do the
polymorphic conversion yourself, you just need to do it at injection
time instead of extraction time:

int main()
{
         B *b = new B(); //create derived class
         boost::any n(static_cast<A*>(b)); // place inside boost::any

         A* a = boost::any_cast<A*>(n);
}

HTH.

--
-- Grafik - Don't Assume Anything
-- Redshift Software, Inc. - http://redshift-software.com
-- rrivera/acm.org - grafik/redshift-software.com
-- 102708583/icq - grafikrobot/aim - grafikrobot/yahoo

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net