asio(四)、时间类封装

官网教程:https://think-async.com/Asio/asio-1.26.0/doc/asio/tutorial/tuttimer4.html

在本教程中,我们将看到如何使用类成员函数作为完成处理程序。该程序的执行方式应与教程Timer.3中的教程程序相同。

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

我们没有像以前的教程程序那样定义一个自由函数print作为完成处理程序,而是定义了一个名为printer的类。

class printer
{
public:

这个类的构造函数将引用io_context对象,并在初始化timer_成员时使用它。用于关闭程序的计数器现在也是该类的成员。

  printer(asio::io_context& io)
    : timer_(io, asio::chrono::seconds(1)),
      count_(0)
  {

boost::bind函数与类成员函数和自由函数一样适用。由于所有非静态类成员函数都有一个隐式this参数,因此我们需要将其绑定到函数。与教程Timer.3中一样,boost::bind将我们的完成处理程序(现在是一个成员函数)转换为一个函数对象,该函数对象可以被调用,就好像它有签名void(const asio::error_code&)一样。

您会注意到,这里没有指定asio::placeholders::error占位符,因为打印成员函数不接受错误对象作为参数。

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

在类析构函数中,我们将打印出计数器的最终值。

  ~printer()
  {
    std::cout << "Final count is " << count_ << std::endl;
  }

打印成员函数与教程Timer.3中的打印函数非常相似,只是它现在对类数据成员进行操作,而不是将计时器和计数器作为参数传入。

  void print()
  {
    if (count_ < 5)
    {
      std::cout << count_ << std::endl;
      ++count_;

      timer_.expires_at(timer_.expiry() + asio::chrono::seconds(1));
      timer_.async_wait(boost::bind(&printer::print, this));
    }
  }

private:
  asio::steady_timer timer_;
  int count_;
};

主函数比以前简单得多,因为它现在在正常运行io_context之前声明了一个本地打印机对象。

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

  return 0;
}
#include <iostream>
#include <asio.hpp>
#include <boost/bind/bind.hpp>

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

  ~printer()
  {
    std::cout << "Final count is " << count_ << std::endl;
  }

  void print()
  {
    if (count_ < 5)
    {
      std::cout << count_ << std::endl;
      ++count_;

      timer_.expires_at(timer_.expiry() + asio::chrono::seconds(1));
      timer_.async_wait(boost::bind(&printer::print, this));
    }
  }

private:
  asio::steady_timer timer_;
  int count_;
};

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

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值