[boost.Asio tutorial] Using a member function as a handler

2019. 8. 14. 21:38PL/C++

이번 튜토리얼에서는 클래스 멤버 함수를 callback handler로 사용하는 방법에 대해서 알아볼 것이다. 

 

중요하게 볼 점은 print 함수를 호출할 때는 공통적인 매개변수가 없기 때문에 

void print(const boost::system::error_code&, boost::asio::deadline_timer *t, int *count)

다음과 같이 타이머와 카운터 변수를 전달해야 했지만, 이제는 클래스 안의 멤버 변수에 포함되어 있으므로 그럴 필요가 없다. 그리고 클래스 멤버 함수는 non-static 함수인 free function으로 분류해서 boost::asio::placeholders::error는 포함하지 않는다고 나와있다. 따라서 따로 error object를 파라미터로 포함하지 않아도 된다

 

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

using namespace std;

class Printer {
private:
	int count_;
	boost::asio::deadline_timer timer_;

public:
	Printer(boost::asio::io_context &io) :
		count_(0), timer_(io, boost::posix_time::seconds(1))
	{
		timer_.async_wait(boost::bind(&Printer::print, this));
	}
	~Printer() {
		cout << "Final count is " << count_ << '\n';
	}

	void print() {
		if (count_ < 5) {
			cout << count_ << '\n';
			count_++;

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

int main(void) {
	boost::asio::io_context io;
	Printer p(io);
	io.run();
	return 0;
}

 

[출처] https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/tutorial/tuttimer4.html