Boost C++回调返回数据的语法问题求助
Boost C++回调传递返回数据的语法问题
我在实现Boost C++回调时,需要从回调中获取返回数据(向回调传递参数),但遇到了语法问题。当前无返回值的回调可以正常触发,但切换为代码中注释的带参数写法后无法正常工作,求指导。
无返回值时的输出:
j1 : 1 j2 : 1 j1 : 2 j2 : 2 j1 : 3 acceptResult j1 : 4 acceptResult
问题原因与解决步骤
核心问题是绑定回调时未为参数预留占位符,导致函数签名不匹配。需要修改以下几个关键点:
- 启用带参数的
callback类型定义 - 调整
A::acceptResult为带参数的函数 - 在B类中调用回调时传入参数
- 使用Boost Bind的占位符
_1匹配回调的参数
修改后的完整代码
#include <iostream> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/asio.hpp> #include <map> #include <string> //typedef boost::function<void()> callback; typedef boost::function<void(std::string)> callback; // 启用带参数的回调类型 class B { public: B(boost::asio::io_service& io, std::string name_, int target_, callback call_) : timer_(io, boost::posix_time::seconds(1)), count(1), target(target_), name(name_), call(call_) { timer_.async_wait(boost::bind(&B::print, this)); } ~B() { std::cout << "Final count is " << count << "\n"; } void print() { if (count < target) { std::cout << name << " : " << count << "\n"; ++count; timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1)); timer_.async_wait(boost::bind(&B::print, this)); } else { //call(); call(name); // 调用回调时传入job名称参数 } } private: callback call; boost::asio::deadline_timer timer_; int count; int target; std::string name; }; class A { private: std::map<std::string, B*> jobs; boost::asio::io_service io; public: //void acceptResult() void acceptResult(std::string jobID_) // 修改为带参数的函数 { //std::cout << "acceptResult" << std::endl; std::cout << "acceptResult from job : " << jobID_<< std::endl; // 释放对应job资源 delete jobs.at(jobID_); auto it = jobs.find(jobID_); jobs.erase(it); } void newJob(std::string jobID_, unsigned int target) { // 使用_1占位符,为回调的参数预留位置 B *b = new B(io, jobID_, target, boost::bind(&A::acceptResult, this, _1)); jobs.insert({jobID_, b}); } void run() { io.run(); } }; int main() { A a; a.newJob("j1", 5); a.newJob("j2", 3); a.run(); return 0; }
修改后的输出示例
j1 : 1 j2 : 1 j1 : 2 j2 : 2 j1 : 3 acceptResult from job : j2 Final count is 3 j1 : 4 acceptResult from job : j1 Final count is 5
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

