boost :: bind - 获取成员变量的写权限? (像boost :: multi_index :: member)

时间:2012-10-15 20:05:04

标签: boost boost-bind boost-multi-index

出于好奇,有没有办法通过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

1 个答案:

答案 0 :(得分:2)

是的,有可能:

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