[C++-sig] Automatic conversions for const std::string&

Hans Meine meine at informatik.uni-hamburg.de
Fri Dec 22 16:20:02 CET 2006

On Thursday, 21. December 2006 19:58, Gabriel Becedillas wrote:
> I have a lot of functions returning "const std::string&". Every time I
> wrap one of those I have to do it like this:
> class_.def("name", &someclass::bla,
> boost::python::return_value_policy<boost::python::copy_const_reference>()
> );
> Is there a way to register a return value conversion for "const
> std::string&" so I can omit the
> "boost::python::return_value_policy<boost::python::copy_const_reference>()"
> every time I have to wrap this functions ? I wan't those strings to be
> copied to python as new strings (I don't want to hold a pointer to them).

I think I would rather use

boost::python::return_value_policy<boost::python::copy_const_reference> ccr;

class_.def("name", &someclass::bla, ccr);
class_.def("name2", &someclass::bla2, ccr);

(You could also derive your own class_-like wrapper from class_ and add def() 
overloads accordingly, or "defs" for "define string-returning function", but 
the latter would not improve much then, and the former is more work.)

Ciao, /  /
    /  / ANS

More information about the Cplusplus-sig mailing list