如何在 steady_timer::async_wait 中用 lambda 替换 std::bind

How to replace std::bind with lambda within steady_timer::async_wait

Live On Coliru

#include <iostream>
#include <boost/asio.hpp>
#include <functional>

class printer
{
public:
  printer(boost::asio::io_context& io)
    : timer_(io, boost::asio::chrono::seconds(1))
  {
    timer_.async_wait(std::bind(&printer::print, this));
    // timer_.async_wait([this]() {
    //     print();
    // });
  }

  void print()
  { 
      std::cout << "hello world" << std::endl;
  }

private:
  boost::asio::steady_timer timer_;
};

int main()
{
  boost::asio::io_context io;
  printer p(io);
  io.run();

  return 0;
}

我尝试替换以下行:

timer_.async_wait(std::bind(&printer::print, this));

 timer_.async_wait([this]() {
     print();
 });

但是失败了,编译器报如下错误:

main.cpp: In constructor 'printer::printer(boost::asio::io_context&)':
main.cpp:12:22: error: no matching function for call to 'boost::asio::basic_waitable_timer<std::chrono::_V2::steady_clock>::async_wait(printer::printer(boost::asio::io_context&)::<lambda()>)'
   12 |     timer_.async_wait([this]() {
      |     ~~~~~~~~~~~~~~~~~^~~~~~~~~~~
   13 |         print();
      |         ~~~~~~~~      
   14 |     });
      |     ~~  

问题> 用 lambda 表达式重写 std::bind 的正确方法是什么?

谢谢

您的 lambda 没有所需的签名。

基于 boost documentation, the callback takes a const boost::system::error_code& argument. std::bind lets you be a bit looser in the function signature (),但 lambda 表达式需要完全匹配。

下面的代码似乎对我有用

    timer_.async_wait([this](auto const &ec) {
        print();
    });