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

David Abrahams david.abrahams at rcn.com
Sat Apr 6 01:24:13 CEST 2002


----- Original Message -----
From: "Peter Bienstman" <pbienst at MIT.EDU>

> Well, something like this doesn't seem to work:
>
>
> #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(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&>()))
>     ;
>
> }
>
> >>> 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







More information about the Cplusplus-sig mailing list