繁体   English   中英

为什么绑定函数不适用于解引用迭代器?

[英]Why bind function does not work with dereferencing iterator?

我是 C++ 编程的新手。 我正在使用bind函数将对象与类设置器绑定并调用设置器。 当我尝试将迭代器取消引用为bind函数中的对象时,对象变量不会改变。 但是,当我只是将迭代器作为bind函数中的对象传入时,它就可以工作。 谁能向我解释为什么会这样?

string name;
char temp;
bool manager;

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Employee Name: ", getline(cin, name, '\n');

auto employee = find(employee_list.begin(), employee_list.end(), name);
if (employee != employee_list.end()){

    cout << "Change Detail " << endl;
    cout << "1. Name" << endl;
    cout << "2. Phone" << endl;
    cout << "3. Address" << endl;

    string choice;
    string new_value;
    map<string, function<void(string_view)>> subMenu;

    do{
        cout << "Selection: ", cin >> choice;

        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "New Value: ", getline(cin, new_value, '\n');

        subMenu = {
            {"1", bind(&Employee::set_name, *employee, new_value)},
            {"2", bind(&Employee::set_phone, *employee, new_value)},
            {"3", bind(&Employee::set_address, *employee, new_value)}
        };

        if(subMenu.find(choice) == subMenu.end()){
            cout << "\nSelection Not Found\n" << endl;
        }
    }
    while (subMenu.find(choice) == subMenu.end());

    auto selection = subMenu.find(choice)->second;
    selection(new_value);

    cout << "Operation complete" << right << endl;  
}

设置器功能:

void Employee::set_name(std::string_view p_name){
    std::cout << "Set Name: " << std::endl;
    std::cout << "Old value: " << name << std::endl;
    name = p_name;
    std::cout << "New value: " << name << std::endl;
    
}

void Employee::set_phone(std::string_view p_phone){
    phone = p_phone;
}

void Employee::set_address(std::string_view p_address){
    address = p_address;
}

当我尝试使用*employee时,它​​不会更改对象的变量。 但是,当我只传入find函数返回的迭代器( employee )时,它可以工作,但我不明白。 我知道我可以使用 if/else 语句轻松地做到这一点,但我想了解更多关于 c++ 的信息。

cprefrence上的std::bind页面所述:

bind 的参数被复制或移动,并且永远不会通过引用传递,除非包装在std::refstd::cref中。

如果您想更改*employee指向的对象,您应该将它们包装在std::reference_wrapper中,例如通过辅助函数std::ref

subMenu = {
    {"1", bind(&Employee::set_name, std::ref(*employee), new_value)},
    {"2", bind(&Employee::set_phone, std::ref(*employee), new_value)},
    {"3", bind(&Employee::set_address, std::ref(*employee), new_value)}
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM