asio 0.1.5 Main Page | Class Index | Member Index | Tutorial

Tutorial Part 4 - Using a member function as a handler

In this part of the 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 Part 3.

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

Step 1. 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:

Step 2. The constructor of this class will take a reference to the demuxer 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(asio::demuxer& d)
    : timer_(d, asio::timer::from_now, 1),
      count_(0)
  {

Step 3. 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 Part 3, boost::bind converts our callback handler (now a member function) into a function object that matches the signature void().

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

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

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

Step 5. The print member function is very similar to the print function from Part 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_.set(asio::timer::from_existing, 1);
      timer_.async_wait(boost::bind(&printer::print, this));
    }
  }

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

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

int main()
{
  asio::demuxer d;
  printer p(d);
  d.run();

  return 0;
}

See the Source listing for Tutorial Part 4
Return to the Tutorial Index
Go back to Tutorial Part 3 - Binding arguments to a handler