1

只是出于好奇,有没有办法通过 获得对成员变量的写访问权限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
4

1 回答 1

2

是的,有可能:

// Read-write Access
boost::function<string&(Test*)> nameSetter =
                                      boost::bind<std::string&>(&Test::name, _1);
nameSetter(&test) = "test";
cout << ref << "\n";
于 2012-10-16T02:54:38.883 回答