【问题标题】:C++ Defining a function which works with lambda closuresC++ 定义一个与 lambda 闭包一起使用的函数
【发布时间】:2015-03-21 21:55:27
【问题描述】:

我在确定 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 闭包参数(可选),但到目前为止我失败了。你能帮我弄清楚吗?

谢谢!

【问题讨论】:

标签: c++ lambda closures


【解决方案1】:

无捕获 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 *)>);
    

【讨论】:

  • 前面有错字! “类型名称”应该是“类型名称”。不过答案很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多