簡體   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