【发布时间】:2012-02-21 07:36:55
【问题描述】:
我正在尝试 Boost.Asio 文档中的不同教程,并尝试用 C++11 替换 boost 组件。但是,我在Timer.5 - Synchronising handlers in multithreaded programs 中使用 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;
}
我尝试将boost::thread 替换为std::thread,将boost::bind 替换为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();
}
当使用 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&& ...)
考虑到我没有使用任何 boost::asio::placeholders(如此 stackoverflow 问题 Should std::bind be compatible with boost::asio? 中所述),此错误来自哪里?
【问题讨论】:
-
由于您已经在使用 C++11:对于您来说,lambdas 可能是
std::bind的替代品,例如std::thread t([&io]() { io.run(); });。这完全避免了重载决议。
标签: c++ boost c++11 boost-asio boost-bind