Timer.4-使用成员函数作为一个作为回调句柄
#include "stdafx.h" #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> class printer { public: printer(boost::asio::io_service& io) : timer_(io, boost::posix_time::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_.expires_at() + boost::posix_time::seconds(1)); timer_.async_wait(boost::bind(&printer::print, this)); } } private: boost::asio::deadline_timer timer_; int count_; }; int main() { boost::asio::io_service io; printer p(io); io.run(); return 0; }
在本教程中我们将看到如何使用类的成员函数作为回调处理程序。程序就应执行相同到教程程序从教程 Timer.3。 #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> 而不是作为回调处理程序定义print免费功能,像我们一样在早些时候的教程程序中,我们现在定义一个名为printer类. class printer { public: 此类的构造函数将采取对 io_service 对象的引用,并使用它时初始化timer_成员。现在,用于关闭该程序的计数器也是类的一个成员。 printer(boost::asio::io_service& io) : timer_(io, boost::posix_time::seconds(1)), count_(0) { 推动:: bind() 功能与免费的功能一样的效果一样好与类的成员函数。由于所有非静态类成员函数中有this的隐式参数,我们需要this。在教程的 Timer.3,boost:: bind() 转换为我们回调处理程序 (现在成员函数) 好像它具有签名可以调用一个函数对象void(const boost::system::error_code&). 你会注意到,boost::asio::placeholders::error 占位符不在此处,指定print的成员函数不接受错误对象作为参数。 timer_.async_wait(boost::bind(&printer::print, this)); } 在类的析构函数中我们将打印出最终计数器的值。 ~printer() { std::cout << "Final count is " << count_ << std::endl; } print的成员函数非常类似于print功能从教程 Timer.3,只是它现在运行在类的数据成员,而不是定时器 / 计数器作为参数传递。 void print() { if (count_ < 5) { std::cout << count_ << std::endl; ++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_; }; main功能是更加简单,比之前,因为它现在作为正常运行 io_service 之前声明一个本地printer对象。 int main() { boost::asio::io_service io; printer p(io); io.run(); return 0;
}
执行效果与上一教程相同
