1

我有以下 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 的函数调用运算符永远不会被调用。

这里有什么问题?

谢谢您的帮助!

4

1 回答 1

1

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

auto func = [handler] (const std::error_code& ec) mutable { /* ... */ };
于 2018-04-26T09:07:22.273 回答