出于好奇,有没有办法通过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
答案 0 :(得分:2)
是的,有可能:
// Read-write Access
boost::function<string&(Test*)> nameSetter =
boost::bind<std::string&>(&Test::name, _1);
nameSetter(&test) = "test";
cout << ref << "\n";