简体   繁体   中英

C++ Calling Functions with Parameters from Map

I am playing around with some code that I previously used to call void functions that were parameter-less from a map. However, I can't seem figure out how to pass arguments to the functions I store in a map.

This code should display a menu such as:

1. Edit Record
2. Delete Record
3. Select Another Record
q. Quit

When you select 1,2,3, or "q" the corresponding action in the map should execute.

Here is the code so far:

void DisplaySelectedRecordOptions(Record &rec)
{
    struct SelectedRecordOptions
    {
        string option;
        function<void()> action;
    };

    static const map <string, SelectedRecordOptions> SelectedRecordOptionsTable
    {
        { "1",{ "Edit Record", []() { EditRecord(rec); } } },
        { "2",{ "Delete Record", []() { cout << "WORK IN PROGRESS\n"; } } },
        { "3",{ "Select Another Record", []() { cout << "WORK IN PROGRESS\n"; } } },
        { "q",{ "Quit", []() { cout << "Quit" << "\n";  } } }
    };

    for (auto const& x : SelectedRecordOptionsTable)
    {
        cout << x.first << ". " << (x.second).option << "\n";
    }

    string input;

    while (SelectedRecordOptionsTable.count(input) == 0)
    {
        input = GetInput();
    }

    SelectedRecordOptionsTable.at(input).action();
}

I get the following error trying to run:

an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list

Here is the EditRecord function that I am wanting to try to implement within the map:

void EditRecord(Record &rec)
{
    string description;
    string username;
    string password;

    cout << "Description: ";
    getline(cin, description);
    cout << "Username: ";
    getline(cin, username);
    cout << "Password: ";
    getline(cin, password);

    rec.description = description;
    rec.userName = username;
    rec.password = password;
}

Just make your lambda capture the used variables. Simple way is like this

[&]() { EditRecord(rec); }

The & causes your lambda to capture all variables by reference . There are alternatives which is why this doesn't happen by default. You can research these for yourself .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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