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

C++ Defining a function which works with lambda closures

本文关键字:lambda 闭包 函数 一个 定义 C++      更新时间:2023-10-16

我在计算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 *)>);