|
Boost : |
From: David Abrahams (dave_at_[hidden])
Date: 2002-11-22 07:17:24
Remy Blank <remy.blank_REMOVE_THIS_at_[hidden]> writes:
> Hello Boosters,
>
> I am trying to use dynamic_any to store either objects or pointers to
> (polymorphic) objects.
>
> I am able to extract a pointer to the base class of a contained object:
>
> class B { };
>
> class D: public B { };
>
> void Test()
> {
> any d(D());
>
> B* pb = extract<B>(&d);
> }
>
> This is alread quite useful. However the following code does not work:
>
> void Test2()
> {
> D d;
> any pd(&d);
>
> B* pb = extract<B*>(pd); // pb = 0
>
> char c;
> any AnyChar(c);
>
> int i = extract<int>(AnyChar); // bad_extract
> }
>
> So I have to know the exact type of the contained object and cannot
> rely on implicit conversions (D* -> B* or char -> int) to work.
> This is quite understandable from the fact that any wraps non-class
> types into unrelated classes.
>
> Now my question: is there a way to make these implicit conversions work?
Heh. Boost.Python does it with a complicated class registry and
upcast/downcast system. I don't know if you want to pay for that.
> My best answer at the moment: explicitly register conversion functions
> from one type to the other in a map<pair<type_info const&, type_info const&>, void* (*)(void*)>
> and look up the right function based on the type contained and the
> type requested.
Oh, well, if you're willing to do that...
> But there has to be a better way, hasn't it?
Yes**. The mechanism in Boost.Python allows you to register just the
relationships between adjacent base and derived classes, and it fills
in the rest of the graph. Maybe it's time to refactor this code for
general use in Boost...
The code is in libs/python/src/object/inheritance.cpp.
-Dave
**Of course, there's always the mythical typeid-guided-dynamic-cast
feature I want as a language feature
dynamic_cast<>(void_ptr, src_typeid, dst_typeid)
but sadly it's mythical :(
-- David Abrahams dave_at_[hidden] * http://www.boost-consulting.com Boost support, enhancements, training, and commercial distribution
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk