[C++-sig] Injected constructors

David Abrahams dave at boost-consulting.com
Wed Jul 23 17:48:55 CEST 2003


It's already possible to inject new methods into a Python class
wrapper that are not in the underlying class:
    
    #include <vector>
    struct  X
    {
       std::vector<int> v;
    };

    int size(X& self) { return self.v.size(); }

    BOOST_PYTHON_MODULE(test)
    {
       class_<X>("X")
          .def("size", size)
          ;
    }

    >>> x = X()
    >>> x.size()
    0

Currently, there's no easy way to do the same thing for constructors,
without intruding on the underlying class or writing a wrapper class
which repeats *all* of the base constructors and adds new ones.

I am about to add just such a facility:

    std::auto_ptr<X> x_factory(PyObject* self, int n)
    {
        std::auto_ptr<X> x(new X);
        x->v.resize(n);
        return x;
    }

    BOOST_PYTHON_MODULE(test)
    {
       class_<X>("X")
          .def("size", size)
          .def("__init__", init_factory(x_factory))
          ;
    }

    >>> x = X(30)
    >>> x.size()
    30

init_factory creates a python callable object which calls its function
argument and injects the resulting object into a holder in the self
argument.

I'm not in love with the "init_factory" name.  Anyone have a better idea?

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list