【发布时间】:2013-11-29 04:47:35
【问题描述】:
我正在学习 Boost.Asio,但我有一个关于 boost::asio::deadline_timer async_wai 的问题。这是来自boost主页的代码:
//
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#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_ << "\n";
}
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_;
};
int main()
{
boost::asio::io_service io;
printer p(io);
io.run();
return 0;
}
async_wait 需要这样的函数签名:
void handler(
const boost::system::error_code& error // Result of operation.
);
但是在这个圆顶中,是timer_.async_wait(boost::bind(&printer::print, this));,签名是void print(printer*),它是如何工作的?
请帮帮我,谢谢。
【问题讨论】:
-
我会使用
std::bind并尽量少使用boost的东西(我在我的项目中使用boost.asio并且只包括boost/asio.hpp)。请参阅stackoverflow.com/a/17414563/2176127 了解如何使用std::bind而不是boost::bind。 -
See this article 以更好地了解 `bind 的工作原理。
-
@IgorR。很棒的文章!