[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<void(void)> timer_fn_type; //**version 1 typedef boost::function<void(const boost::system::error_code&)> timer_fn_type; //**version 2 boost::asio::deadline_timer timer_; timer_fn_type timer_fn_; int count_; }; The error report for version 1 is "term does not evaluate to a function taking 1 arguments" at boost/asio/detail/bind_handler.hpp line 39. 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. Thanks for any insight. -evan

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