aut*_*hir 18 c++ boost boost-bind boost-asio c++11
我在Boost.Asio文档中尝试了不同的教程,并试图用C++ 11替换boost组件.但是,我在Timer.5中使用std :: bind时出错了 - 在多线程程序中同步处理程序.这是建议的代码:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class printer { /* Not relevent here */ };
int main()
{
boost::asio::io_service io;
printer p(io);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
io.run();
t.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试图替换boost::threadby std::thread和boost::bindby std::bind.这是我的代码:
#include <functional>
#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class printer { /* Not relevent here */ };
int main() {
boost::asio::io_service io;
printer p(io);
std::thread t(std::bind(&boost::asio::io_service::run, &io));
io.run();
t.join();
}
Run Code Online (Sandbox Code Playgroud)
在使用GCC 4.7进行编译时,我得到了这个编译时错误:
g++ -std=c++0x main.cpp -lboost_system -lboost_date_time -lpthread
main.cpp: In function ‘int main()’:
main.cpp:52:60: erreur: no matching function for call to ‘bind(<unresolved overloaded function type>, boost::asio::io_service*)’
main.cpp:52:60: note: candidates are:
/usr/include/c++/4.6/functional:1444:5: note: template<class _Functor, class ... _ArgTypes> typename std::_Bind_helper::type std::bind(_Functor&&, _ArgTypes&& ...)
/usr/include/c++/4.6/functional:1471:5: note: template<class _Result, class _Functor, class ... _ArgTypes> typename std::_Bindres_helper::type std::bind(_Functor&&, _ArgTypes&& ...)
Run Code Online (Sandbox Code Playgroud)
这个错误来自何处,考虑到我没有使用任何boost::asio::placeholders(如此stackoverflow问题中的解释,std :: bind应该与boost :: asio兼容吗?)?
Die*_*ühl 36
所述boost::asio::io_service::run()成员函数被重载:一个版本没有参数而另一个版本采用一个参数.也就是说,获取of的地址boost::asio::io_service::run需要一个上下文,其中编译器可以直接推导出函数的签名.但是,std::bind()并不需要做演绎魔法,而似乎boost::bind()试图找到匹配的重载,即它的第一个参数类型似乎很容易被约束(假设增强示例确实编译).
解决这个问题你可以明确指定第一个参数的类型std::bind()(它也应该使用boost::bind()),例如:
std::bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io);
Run Code Online (Sandbox Code Playgroud)
我没有检查标准是否有任何要求,但如果它确实没有做任何要求,我会考虑一个实现,虽然它的工作量较少,但它并没有通过英雄来推断出论证类型的质量更好:它需要用户编写的代码可以在另一个编译器上编译.
Rio*_*iot 16
简单来说,在C++ 11之后,你可以使用lambdas来避免所有的faff并大大简化整个事情.老人:
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
Run Code Online (Sandbox Code Playgroud)
或者std :: version:
std::thread t(boost::bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io_service));
Run Code Online (Sandbox Code Playgroud)
变得公正:
std::thread t([&io_service](){io_service.run();});
Run Code Online (Sandbox Code Playgroud)