[boost.Asio tutorial] Using a member function as a handler
2019. 8. 14. 21:38ㆍPL/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
'PL > C++' 카테고리의 다른 글
연산자를 오버로딩하는 두 가지 방법 (0) | 2019.08.19 |
---|---|
연산자 오버로딩 =과 == (0) | 2019.08.19 |
[boost.Asio tutorial] Binding arguments to a handler (0) | 2019.08.14 |
[boost.Asio tutorial] Using a timer asynchronously (0) | 2019.08.13 |
[boost.Asio tutorial] Using a timer synchronously (0) | 2019.08.13 |