Lv.的博客

Timer.4 - Using a member function as a handler

 

In this tutorial we will see how to use a class member function as a callback handler. The program should execute identically to the tutorial program from tutorial Timer.3.

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

Instead of defining a free function print as the callback handler, as we did in the earlier tutorial programs, we now define a class called printer.

class printer
{
public:

The constructor of this class will take a reference to the io_service object and use it when initialising the timer_ member. The counter used to shut down the program is now also a member of the class.

  printer(boost::asio::io_service& io)
    : timer_(io, boost::posix_time::seconds(1)),
      count_(0)
  {

The boost::bind() function works just as well with class member functions as with free functions. Since all non-static class member functions have an implicit this parameter, we need to bind this to the function. As in tutorial Timer.3, boost::bind() converts our callback handler (now a member function) into a function object that can be invoked as though it has the signature void(const boost::system::error_code&).

You will note that the boost::asio::placeholders::error placeholder is not specified here, as the print member function does not accept an error object as a parameter.

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

In the class destructor we will print out the final value of the counter.

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

The print member function is very similar to the print function from tutorial Timer.3, except that it now operates on the class data members instead of having the timer and counter passed in as parameters.

  void print()
  {
    if (count_ < 5)
    {
      std::cout << count_ << "\n";
      ++count_;

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

private:
  boost::asio::deadline_timer timer_;
  int count_;
};

The main function is much simpler than before, as it now declares a local printer object before running the io_service as normal.

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

  return 0;
}

See the full source listing

Return to the tutorial index

Previous: Timer.3 - Binding arguments to a handler

Next: Timer.5 - Synchronising handlers in multithreaded programs

posted @   Avatarx  阅读(163)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示