c++ - 如何在 stable_timer::async_wait 中用 lambda 替换 std::bind

标签 c++ lambda c++14

<强> 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 ,回调采用 const boost::system::error_code&争论。 std::bind让您可以在函数签名 ( Why std::bind can be assigned to argument-mismatched std::function? ) 中宽松一点,但 lambda 需要完全匹配。

以下代码似乎对我有用

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

关于c++ - 如何在 stable_timer::async_wait 中用 lambda 替换 std::bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71462073/

相关文章:

c# - 如何编写 LINQ 查询以从具有给定匹配 ID 集的集合中进行选择

c++ - 如何读取二进制数作为输入?

c++ - 编译器无法推断返回类型?

c++ - 为什么在此代码中出现运行时错误SIGSEGV

c++ - 为Tab Control处理WM_PAINT事件也需要手动绘制项目?

c++ - 使用occi在c++中连接到oracle 10g时出现ora 24960错误

lambda - 如果 DynamoDb 表已存在,如何继续部署

c++ - 模板类中的内联虚方法

c++ - 把 main 放在哪里,在那里写什么?

java - Java 8 中 '()->{}' 的类型是什么?