Boost logo

Boost Users :

From: David Abrahams (dave_at_[hidden])
Date: 2007-09-21 14:58:55


on Fri Sep 14 2007, Dan Posluns <dan-AT-danposluns.com> wrote:

> Okay, I'm a lot closer to my goal of having an automated factory of
> objects that are dynamically polymorphic but have their inheritance set
> up through static means.
>
> What I have now is something like this:
>
> // My factory template
> template<class Base, class Derived>
> struct Factory
> {
> Base *create() { return new Derived(); }
> };
>
> // My vector of factories for the different Derived types
> typedef mpl::vector<
> Factory<Base, Derived1>,
> Factory<Base, Derived2>,
> Factory<Base, Derived3> > MyFactories;
>
>
> (I actually use MPL to automatically cross and combine different
> classes, which is pretty cool.)
>
>
> Now I could create a vector of the same length with every type as a
> pointer to a Factory function, and with Fusion I could probably
> instantiate it (although I haven't got that working yet). But that still
> wouldn't get me what I want, which is a table of those factory functions
> that I can index into at run-time.
>
> Can anyone suggest a technique for doing this?

If you want to index it at runtime and get anything more than a void*
back, you need to add dynamic polymorphism somewhere so that you have
a common interface through which all these factories can be used. One
possibility is to create a FactoryBase class with virtual functions
and derive all your Factory templates from it. As long as the
factories are all creating the same Base, you should be OK. I would
then use fusion to convert the mpl vector into a tuple (so you don't
have to dynamically allocate all the Factories) and use
fusion::for_each to fill up an array of FactoryBase pointers.

HTH,

-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com
The Astoria Seminar ==> http://www.astoriaseminar.com

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