[C++-sig] V2: conversions through constructors?

David Abrahams david.abrahams at rcn.com
Tue Apr 9 17:57:44 CEST 2002


Hi Peter,

What you forgot was to explicitly define the default __init__ functions
for your types. Please see bienstman4.cpp in the CVS for an example.

The __init__ function is the mechanism that actually creates the C++
object within the Python object, and none of the member functions of
Expression can work on a Python object until there is a C++ Expression
instance. I have some ideas about how this might be made automatic, but
in the meantime, you need to add def_init() to your class.

Regards,
Dave

P.S. I also plan to improve the error reporting for cases like this ;-)

----- Original Message -----
From: "Peter Bienstman" <pbienst at MIT.EDU>
To: <c++-sig at python.org>
Sent: Monday, April 08, 2002 9:33 AM
Subject: Re: [C++-sig] V2: conversions through constructors?


> I changed 'add' to accept const Term&, but still the same behaviour..
>
>
> #define BOOST_PYTHON_DYNAMIC_LIB
> #define BOOST_PYTHON_V2
>
> #include <boost/python/module.hpp>
> #include <boost/python/class.hpp>
> #include <boost/python/implicit.hpp>
> #include <boost/mpl/type_list.hpp>
>
> struct T1 {};
>
> struct Term {Term(T1&) {} };
>
> struct Expression {void add(const Term&) {} };
>
> BOOST_PYTHON_MODULE_INIT(m)
> {
>   using namespace boost::python;
>   using boost::mpl::type_list;
>
>   implicitly_convertible<T1,Term>();
>
>   module m("m");
>
>   m
>     .add(class_<Expression>("Expression")
>          .def("add", &Expression::add))
>     .add(class_<T1>("T1"))
>     .add(class_<Term>("Term")
>          .def_init(type_list<T1&>()))
>     ;
>
> }
>
> On Fri, 2002-04-05 at 18:24, David Abrahams wrote:
> >
> > ----- Original Message -----
> > From: "Peter Bienstman" <pbienst at MIT.EDU>
> >
> > > Well, something like this doesn't seem to work:
> > > >>> from m import *
> > > >>> t1 = T1()
> > > >>> e = Expression()
> > > >>> e.add(t1)
> > > Traceback (most recent call last):
> > >   File "<stdin>", line 1, in ?
> > > TypeError: bad argument type for built-in operation
> >
> >
> > The corresponding C++ doesn't work either:
> >
> >     T1 t1;
> >     Expression e;
> >     e.add(t1); // error
> >
> > Because your arguments are non-const references, you're telling the
> > library that they don't bind to temporaries. Thus, they require
lvalue
> > converters, and the converters generated by implicitly_convertible<>
are
> > always rvalue converters.
> >
> > If you change your add() function to accept a Term const&,
everything
> > will work.
> >
> >
> > -Dave
>
>
>
>
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig






More information about the Cplusplus-sig mailing list