Tôi đã thử các hướng dẫn differents trong tài liệu Boost.Asio và cố gắng thay thế các thành phần tăng với C++ 11. Tuy nhiên, tôi gặp lỗi khi sử dụng std :: bind trong Timer.5 - Synchronising handlers in multithreaded programs. Đây là mã đề xuất:Tại sao không thể std :: ràng buộc và tăng :: ràng buộc được sử dụng thay thế cho nhau trong hướng dẫn này Boost.Asio
#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;
}
tôi đã cố gắng để thay thế boost::thread
bởi std::thread
và boost::bind
bởi std::bind
. Đây là mã của tôi:
#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();
}
Khi biên dịch với GCC 4.7, tôi nhận này lỗi thời gian biên dịch:
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&& ...)
đâu lỗi này đến từ, có tính đến mà tôi đã không sử dụng bất kỳ boost::asio::placeholders
(như giải thích trong câu hỏi stackoverflow này Should std::bind be compatible with boost::asio?)?
Có thể trùng lặp: xem http://stackoverflow.com/questions/8924149/should-stdbind-be-compatible-with-boostasio). – mark
Vì bạn đã sử dụng C++ 11: lambdas có thể là giải pháp thay thế để 'std :: bind' cho bạn, ví dụ,' std :: thread t ([& io]() {io.run();}); '. Điều này tránh hoàn toàn quá tải độ phân giải – mavam