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

时间:2019-03-27 06:41:12

标签: c++

我正在处理一些代码,这些代码以前用于调用void函数,这些函数在地图中没有参数。但是,我似乎无法弄清楚如何将参数传递给存储在映射中的函数。

此代码应显示一个菜单,例如:

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

当您选择1,2,3或“ q”时,地图中的相应动作应执行。

这是到目前为止的代码:

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();
}

尝试运行时出现以下错误:

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

这是我想尝试在地图中实现的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;
}

1 个答案:

答案 0 :(得分:2)

只需让您的lambda捕获使用的变量即可。简单的方法就是这样

&

from users.models import UserMessage def notifications(request): if not request.user.is_anonymous: notifications = UserMessage.objects.filter( receiver=request.user, read=False) ctx = { "notifications": notifications, "notifications_number": notifications.count() } return ctx return {} 使您的lambda通过引用捕获所有变量 。有替代方法,这就是为什么默认情况下不会发生这种情况。您可以Unable to redefine properties of the window object