[asio] question about binding member function as WaitHandler
The documentation's example 4 uses boost::bind to create a handler for
deadline_timer::async_wait(). The function bound, printer::print(), takes no
parameter and the code compiles and works fine. I tried modifying the
example so that, instead of creating a new, temporary function object in
place for each call to async_wait(), it creates a single boost::function
object as a data member in the ctor, which is then passed in each call.
Using MSVS 2005 and boost 1.37 I found that I had to add a
boost::system::error_code& parameter to print() in order to get it to
compile. Here is my modified printer class, with both the non-working
(version 1) and working (version 2) code to, I hope, make this clearer.
class printer
{
public:
printer(boost::asio::io_service& io)
: timer_(io, boost::posix_time::seconds(1)),
// timer_fn_(boost::bind(&printer::print, this)), //**version 1
timer_fn_(boost::bind(&printer::print, this, _1)), //**version 2
count_(0)
{
timer_.async_wait(timer_fn_);
}
~printer()
{
std::cout << "Final count is " << count_ << "\n";
}
//void print() //**version 1
void print(const boost::system::error_code& /*e*/) //**version 2
{
if (count_ < 5)
{
std::cout << count_ << "\n";
++count_;
timer_.expires_at(timer_.expires_at() +
boost::posix_time::seconds(1));
timer_.async_wait(timer_fn_);
}
}
private:
//typedef boost::function
AMDG eburkitt@gmail.com wrote:
I can see why version 1 won't compile. What I don't understand is why the original example, with its in-place function objects, does.
Boost.Bind ignores any arguments that are not used. void f() {} boost::bind(f)(2, 3); // ok. In Christ, Steven Watanabe
participants (2)
-
eburkitt@gmail.com
-
Steven Watanabe