2012-10-15 61 views
1

出於好奇,有沒有辦法通過boost::bind獲得對成員變量的寫權限?我可以通過boost::multi_index::member得到它,但只是想知道其他方法。boost :: bind - 獲得對成員變量的寫入權限? (像boost :: multi_index :: member)

例子:

#include <string> 
#include <boost/function.hpp> 
#include <boost/bind.hpp> 
#include <boost/multi_index/member.hpp> 

using namespace std; 

struct Test 
{ 
    string name; 
    Test(const string &name) 
     : name(name) 
    { } 
}; 

int main() 
{ 
    Test test("Bob"); 
    boost::multi_index::member<Test, string, &Test::name> nameMember; 
    string &ref = nameMember(test); 
    cout << ref << "\n"; 
    // Write Access 
    ref = "Tim"; 

    // Read-only Access 
    boost::function<const string& (Test*)> nameGetter = boost::bind(&Test::name, _1); 
    cout << nameGetter(&test) << "\n"; 

    return 0; 
} 

輸出:

Bob 
Tim 

回答

2

是的,這是可能的:

// Read-write Access 
boost::function<string&(Test*)> nameSetter = 
             boost::bind<std::string&>(&Test::name, _1); 
nameSetter(&test) = "test"; 
cout << ref << "\n"; 
+0

就像一個魅力 - 謝謝! – eacousineau