Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-11-21 09:44:47


From: "Anthony Liguori" <anthony_at_[hidden]>
[...]
> So I wrote up a class that provided virtual constructor functionality.
> It actually allows for types to be treated as objects including storing
> types in any STL container. This allows for really advanced factory
> algorithms and all sorts of fun stuff. The basic usage is as follows:
>
> struct A
> {
> A(int a);
> };
>
> struct B : public A
> {
> B(int a);
> };
>
> typedef factory<A, int> FactoryA;

typedef function<A* (int)> FactoryA;

> FactoryA b = FactoryA::create<B>();

template<class T> struct constructor
{
    template<class A1> T * operator()(A1 const & a1)
    {
        return new T(a1);
    }
};

FactoryA b = constructor<B>();

> FactoryA c;
>
> A *a = b(10); // Returns new B(10)
> c = b;
> delete a;
> a = c(15); // Returns new B(10)

;-)

Change 'T*' to auto_ptr<T> or shared_ptr<T> according to taste.


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