[C++-sig] boost python class member getter/setter same name different only by constness
Jim Bosch
talljimbo at gmail.com
Fri Oct 3 19:23:33 CEST 2014
On Fri, Oct 3, 2014 at 1:15 PM, Stefan Seefeld <stefan at seefeld.name> wrote:
> On 2014-10-03 12:56, MM wrote:
> > yes i did that.
> >
> > class C {
> > public:
> > const std::string& get_name() const;
> > void set_name(const std::string&);
> > private:
> > std::string name_;
> > };
> >
> >
> >
> > class_<C>("C").
> > .add_property("name", &C::get_name, &C::set_name);
> >
> >
> > this fails to compile because of unspecified call policies about the
> > string refs.
> >
> >
> > The following, on the other hand, compiles.
> >
> > class C {
> > public:
> > const std::string get_name() const;
> > void set_name(const std::string);
> > ....
> > class_<C>("C").
> > .add_property("name", &C::get_name, &C::set_name);
> >
> >
> > Which policy do I specify? and how do I set it in add_property?
>
> Good question. The policy you want is likely pass-by-value (In Python
> strings are immutable anyhow), however I have no idea how to express
> that with the add_property() call.
> As a quick hack I suggest adding a wrapper function that returns the
> result by-value:
>
> std::string get_name(C &c) { return c.get_name();}
>
> and use that. That's neither elegant nor efficient (if you call it a
> lot), but it may unblock you until you find a real fix.
>
>
To use a call policy here, I *think* you'd pass
return_value_policy<return_by_value>() as the fourth argument to
add_property, but it may be some slight modification of that. In any case,
I suspect that's no more efficient than Stefan's solution in this case.
Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20141003/5811bdb7/attachment-0001.html>
More information about the Cplusplus-sig
mailing list