如何在boost lambda表达式中访问成员变量?

时间:2012-06-27 08:44:35

标签: c++ boost lambda

#include <functional>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>

#include <boost/lambda/lambda.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost::lambda;
using namespace boost::multi_index;
using boost::multi_index_container;
using boost::lexical_cast;

struct student {
    int no;
    string name;
    student(int _no, string _name) : no(_no), name(_name)  { }
};

struct no {};
struct name {};

struct change_name {
    change_name(const string& new_namex) : new_name(new_namex) {}
    void operator()(student& stu) {
        stu.name = new_name;
    }
    private:
    string new_name;
};

int main()
{
    typedef multi_index_container< 
        student,
        indexed_by<
            ordered_non_unique<tag<no>, member<student, int, &student::no>>,
            ordered_non_unique<tag<name>, member<student, string, &student::name>>
        >> student_set;

    typedef student_set::index<no>::type student_set_no;

    student_set students;
    for (int i = 0; i < 10; ++i) 
        students.insert( student(i, "love student " + lexical_cast<string>(i)) );
    student_set_no& no_index = students.get<no>();
    student_set_no::iterator iter = no_index.find(3);

    //suppose i want to change the name to "you",
    no_index.modify(iter, change_name("you"));
    //how could i do this with lambda expression ?
    no_index.modify(iter, _1.name = "you");

    cout << iter->name << endl;
    return 0;
}

如何在未定义函数运算符类的情况下更改名称?

感谢。

0 个答案:

没有答案