lambda表达式中的可调用结构

时间:2018-04-26 08:50:47

标签: lambda c++14 bind

我有以下MWE:

#include <iostream>
#include <system_error>
#include <functional>

struct A
{
  A() : error() {}

  void operator()(const std::error_code& ec)
  {
    error = ec;
    std::cout << "hello world" << std::endl;
  }

  std::error_code error;
};

main()
{
  auto handler = A();
  std::error_code ec = std::error_code();

  auto func = [handler](const std::error_code& ec)
  {
    handler(std::error_code());
  };

  func(ec);
}

编译时,我收到以下错误消息:

error: no match for call to '(const A) (const std::error_code&)' handler(ec);

替换此行
std::bind<void>(handler, std::error_code());

确实编译但是看起来结构A的函数调用操作符永远不会被调用。

这里有什么问题?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

C ++ lambdas默认为const,也就是说它们不能改变捕获的变量。 A::operator()是非常量的,它会改变A。你可以通过使lambda变为可变来解决这个问题:

auto func = [handler] (const std::error_code& ec) mutable { /* ... */ };