gpt4 book ai didi

C++ 定义一个使用 lambda 闭包的函数

转载 作者:行者123 更新时间:2023-11-30 03:55:10 26 4
gpt4 key购买 nike

我在计算 lambda 函数定义时遇到了问题。所以我有这段代码,它工作正常:

auto fnClickHandler = [](Button *button) -> void
{
cout << "click" << endl;
};
button->setEventHandler(MOUSEBUTTONUP, fnClickHandler);

但是我需要在 fnClickHandler 中使用闭包,所以我执行以下代码:

int someParam = 1;

auto fnClickHandler = [someParam](Button *button) -> void
{
cout << "click" << someParam << endl;
};
button->setEventHandler(MOUSEBUTTONUP, fnClickHandler);

现在我得到以下编译错误:

no matching function for call to ‘Button::setEventHandler(BUTTON_EVENT_HANDLERS, nameOfFunctionWhichHostsThisCode::__lambda0&)’|

Button::setEventHandler 函数是这样定义的:

void setEventHandler(int, void (*handler)(Button *));

我想我需要更改该定义以支持 lambda 闭包参数(可选),但到目前为止我都失败了。你能帮我弄清楚吗?

谢谢!

最佳答案

无捕获 lambda 可以隐式转换为具有相同签名的函数指针。这就是您的代码使用非捕获版本的 fnClickHandler 的原因。一旦你有一个捕获的 lambda,你有两个选择:

  1. 创建一个函数模板,让编译器为你推断类型

    template <typename Handler>
    void setEventHandler(int, Handler handler);//You can use either enable_if or static_assert to restrict the types of Handler.
  2. 使用std::function :

    void setEventHandler(int, std::function<void(Button *)>);

关于C++ 定义一个使用 lambda 闭包的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29188508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com