2011-06-10 64 views
1

我有一個C++類,它提出了一個流暢接口,是這樣的:如何使用boost :: python暴露流暢接口的屬性?

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

    private: 
    int m_bar; 
}; 

我想包裹bar()功能在我的Python類的屬性。所以我寫了:

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

但是,編譯器抱怨的制定者,因爲它返回一個Foo&,而不是僅僅void

我也許可以用make_function指定贖回策略但在這裏我堅持:我不知道指定(我甚至不知道,如果這樣的政策存在)的政策。

我能做些什麼來解決這個問題?

以下是編譯器輸出:

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

謝謝。

回答

2

我結束了書面方式下面的模板功能:

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

現在我可以鍵入:

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

,它工作正常:)

+1

的最佳解決方案。 – 2011-06-12 05:04:14