[C++-sig] constructor wrappers?

David Abrahams david.abrahams at rcn.com
Thu May 30 18:05:43 CEST 2002


----- Original Message -----
From: "Ralf W. Grosse-Kunstleve" <rwgk at yahoo.com>


> Would something like the following be possible/desirable?
>
> struct any
> {
>   any(int a=0, int b=0, int c=0) { ... }
> };
>
> any any_from_python_list_or_tuple(PyObject* list_or_tuple)
> {
>   // extract between 0 and 3 int from a list or tuple and use to
construct
>   // an object any_instance.
>   return any_instance;
> }
>
> BOOST_PYTHON_MODULE_INIT(any)
> {
>   boost::python::module this_module("any");
>
>   this_module.add(
>     boost::python::class_<any>("any")
>       .def_init(any_from_python_list_or_tuple)
>   );
>
> }
>
> I guess what I am after is an equivalent of the thin wrappers for member
> functions, some easy-to-use flexible mechanism for "customizing"
constructors
> when they are exposed to Python.

I understand the goal, but I'm not sure what you've got there is the best
solution, for two reasons:

1. It incurs the cost of copying "any"
2. It requires the ability to copy "any", and not all class types are
copyable.

Currently, the way to do this is with a class derived from any:

    boost::python::class_<any,any_wrapper>("any")
        .def_init(args<PyObject*>()) // could use args<tuple> soon


Where

    any_wrapper::any_wrapper(PyObject* ignored, PyObject* seq)

is defined.

However, I'm open to other interface suggestions. I suggest you take a look
at the documentation for make_constructor and the Holder concept to get
started.

Also, part of the formula may involve some extensions to the CallPolicies
concept. For example, we might want to make it possible to specify the
from_python converter that gets used for each argument.

-Dave







More information about the Cplusplus-sig mailing list