Boost logo

Boost :

From: Anthony Liguori (anthony_at_[hidden])
Date: 2003-05-17 17:49:51


Greetings all,

I'm writing to see if there is interest in a little library I wrote a
while back that provides virtual constructor semantics by allowing
constructors to be represented as function objects. I've took an
initial shot at boostifing the code (although the documentation needs a
little work). I think it would go along nicely with the pre-existing
boost::mem_fn() library (either as part of or as a compliment). I've
include a link to the library and also a quick snippet of it's usage:

http://aliguori.dyndns.org/boost/ctor_fn.html

<-- From the docs -->
To use the ctor_fn library, you simply pass the signature of the
constructor you want to receive an object for (as a function type) as
the first template argument to the ctor_fn function. An optional second
template argument can specify an STL compliant allocator class. The
following is an example usage:

    struct A { /* ... */ };
 
    using boost::function;
    using boost::ctor_fn;

    function<A *(const A &)> a_copy = ctor_fn<A *(const A &)>();
    A a;

    /* initialize a */

    A *copy_of_a = a_copy(a)

The initial assignment can also do some more fancy things:

    using boost::smart_ptr;

    function<smart_ptr<A> (const A &)> safe_a_copy = ctor_fn<A *(const A
&)>();

    safe_a_copy(a); // no fears of memory leaks now

<-- end snip -->

As a quick aside, this library would make implementing a factory pattern
incredible easy. One could do something as simple as (assuming two
classes where B inherents from A):

    template <typename BaseSig>
    struct factory
    {
        typedef std::map<std::string, boost::function<BaseSig> > concrete;
    };

    factory<boost::smart_ptr<A> (Widget &a)>::concrete a_factory;

    a_factory["B"] = boost::ctor_fn<B *(Widget &)>();

And of course, my favorite example:

    a_factory["B"] = boost::bind(boost::ctor_fn<B *(Widget &, int)>(),
_1, 45);

This is not a formal submission, I just wanted to see if there's
interest in this before I went through and boostified the
documentation. Also, I've only tested the library on GCC-3.x...

Regards,
Anthony Liguori


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