Boost logo

Boost :

From: Dave Handley (dave.handley_at_[hidden])
Date: 2006-10-10 13:39:30


>
>Vaclav Vesely wrote:
>> Fernando Cacciola wrote:
>>
>>>Vaclav Vesely wrote:
>>>
>>>>I would like to do somethink like this:
>>>>
>>>> class Base {...}
>>>> class Derived: public Base {...}
>>>>
>>>> optional<Base> x = Derived();
>>>> y->call_virtual_functions()
>>>
>>>It looks a lot like Boost.Any.
>>>Have you looked at it?
>>
>>
>> boost::any doesn't support derived classes as well. For example:
>>
>> any x = Derived();
>> any_cast<Base>(x).virtual_function(); // throws bad_any_cast
>>
>> And moreover boost::any is too general. I want to store only values
of Base
>> and its derived classes.
>>
>OK.
>Still, Boost.Any is a lot closer to that than Boost.Optional
>The fundamental issue is that Boost.Optional stores copies of the
values
>in its own storage. That's a key feature of optional<>.
>In your design, as in Boost.Any's, the values are stored in a separate
>storage and the wrapper is merely a proxy to it. So this is more the
job
>of a form of smart pointer (that manages external resources).
>
>IIRC, a few years ago Peter Dimov sketched a polymorphic variant class
>in line with your idea (unless I got it all wrong).
>I can't recall where I saw it though. Peter?
>
>In any event, I think what you need is a new beast rather an extension
>to optional<> because of the separate storage needed to hold the
>polymorphic value.
>

I agree that a new beast would be more appropriate. Last year I wrote a
class similar to boost.variant. It took as template parameters a base
class and a list of derived classes (in an MPL container) and created a
variant that could hold, on the stack, any of the derived objects, but
provide virtual function dispatch through the base class. By virtue of
providing stack storage, it meant you could return polymorphic objects
on the stack - which was the main usage pattern I was after.

If anyone is interested, I may be able to dig out the work and submit it
for some consideration...

Dave Handley


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk