Boost logo

Boost :

From: Steven Brown (swbrown_at_[hidden])
Date: 2002-03-05 22:47:04


I'd like to support handling derived classes as one would values
in my code, e.g., so they can be trivially copied properly and used as their
base class. boost::any seemed to do 90% of what I wanted (virtual clone() to
allow proper copying of the type, wrapper to make it act like a value) but I
can only cast to specific types with it so I can't get a pointer to the base
class if I don't know the type of the derived class.

I tried modifying boost::any to form boost::any_derived<BaseType> to solve my
problem. It's basically an any that has the requirement that all classes it
can contain are derived from BaseType, and supports *, ->, and get() methods
to return a pointer to the BaseType. For example:

boost::any_derived<Parent> object = Child();
object->foo(); (Where foo is a virtual function of Parent)

It was a quick hack so it might have some issues, but it seems to satisfy my
needs. Is there a better or more standard way of doing what I'm trying to do?
 It seems like something that would already exist so I'm worried I'm
overlooking the obvious. :)

The code to boost::any_derived is here if you're interested (yahoogroups can't
take attachments it seems): http://www.cs.ucsd.edu/~sbrown/any_derived.hpp


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