2010-02-14 50 views
3

以下example from boost bind不爲我工作:結合成員變量

#include <boost/bind.hpp> 

struct A 
{ 
    int data; 
}; 

int main() 
{ 
    A a; 
    boost::bind(&A::data, _1)(a) = 1; 
} 

error: assignment of read-only location 'boost::bind [with A1 = boost::arg<1>, M = int, T = A](&A::data, (<unnamed>::_1, boost::arg<1>())).boost::_bi::bind_t<R, F, L>::operator() [with A1 = A, R = const int&, F = boost::_mfi::dm<int, A>, L = boost::_bi::list1<boost::arg<1> >](((A&)(& a)))'

難道我做錯了什麼?編譯器是g ++ 4.4.0

+0

剛剛意識到以上示例鏈接後面的內容:您正在嘗試使用Boost.Bind遵循Boost.Lambda綁定表達式示例。嘗試包括,並使用boost :: lambda :: bind + boost :: lambda :: _ 1來代替。另外,使用boost :: lambda :: var來保存一個引用。 – rjnilsson

回答

2

UncleBens的解決方案是好的,但我想我會補充一點,如果你使用Boost.Lambda問題消失:

#include <boost/lambda/bind.hpp> 

struct A { 
    int data; 
}; 

int main() { 

    namespace bll = boost::lambda; 

    A a; 
    bll::bind(&A::data, bll::_1)(a) = 1; 
} 

所以,如果你用它做boost::mem_fn

#include <boost/mem_fn.hpp> 

struct A { 
    int data; 
}; 

int main() { 

    boost::mem_fn(&A::data)(a) = 1; 
} 
3

該綁定表達式的結果類型是int(或者更確切地說是const int&)。我想你可以override the return type

boost::bind<int&>(&A::data, _1)(a) = 1; 
1

我不知道你想做的事,但真正Boost.Bind重載賦值運算符?如果您想使用返回的函數對象,我認爲你需要做這樣的事情(也指出,「一個」需要通過參考約束)的值1分配給a.data:

#include <boost/bind.hpp> 
#include <boost/ref.hpp> 
#include <cassert> 

void foo() 
{ 
    A a; 

    boost::bind(&A::data, _1)(boost::ref(a), 1); 

    assert(a.data == 1); 
} 

如果您需要使用賦值運算符,我認爲使用Boost.Lambda或Boost.Phoenix將是更好的選擇。