开发者

How to expose a property from a fluent interface with boost::python?

I have a C++ class which presents a fluent interface, something like:

class Foo
{
  public:
    int bar() const { return m_bar; };
    Foo& bar(int value) { m_bar = value; return *this; };

  private:
    int m_bar;
};

I'd like to wrap the bar() functions as a property in my Python class. So I wrote:

class_<Foo>("Foo")
  .add_property(
    "bar",
    (int (Foo::*)())&Foo::bar,
    (Foo& (Foo::*)(int))&Foo::bar
  )
;

But the compiler complains about the setter, because it returns a Foo& instead of just void.

I can probably use make_function to specify a call policy but here I'm stuck: I don't know which policy to specify (I don't even know if such a policy exists).

What can I do to solve this ?

Here is the compiler output:

/usr/include/boost/python/detail/invoke.hpp:88: error: no match for call to '(const boost::python::detail::specify_a_return_value_policy_开发者_StackOverflowto_wrap_functions_returning<Foo&>) (Foo&)'

Thank you.


I ended up writting the following template function:

template <class BaseClass, typename T, BaseClass& (BaseClass::*method)(T)>
void make_nonfluent_setter(BaseClass& self, T value)
{
    (self.*method)(value);
}

And now I can type:

class_<Foo>("Foo")
  .add_property(
    "bar",
    (int (Foo::*)())&Foo::bar,
    make_nonfluent_setter<Foo, int, &Foo::bar>
  )
;

And it works fine :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜