简体   繁体   English

使用Map中的参数进行C ++调用函数

[英]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. 我正在玩一些我以前用来调用从地图上获取无参数的void函数的代码。 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. 当选择1,2,3或“ q”时,地图中的相应动作应执行。

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: 这是我想尝试在地图内实现的EditRecord函数:

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. 只需让您的lambda捕获使用的变量即可。 Simple way is like this 简单的方法是这样的

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

The & causes your lambda to capture all variables by reference . &导致您的lambda 通过引用捕获所有变量。 There are alternatives which is why this doesn't happen by default. 有替代方法,这就是为什么默认情况下不会发生这种情况。 You can research these for yourself . 您可以自己研究这些

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

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