我在找出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后,有两种选择:
创建一个功能模板,让编译器为您推断类型
template <typename Handler>
void setEventHandler(int, Handler handler);//You can use either enable_if or static_assert to restrict the types of Handler.
void setEventHandler(int, std::function<void(Button *)>);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句