需要std :: bind的函數包裝器,它將在包裝函數之前調用,並將參數傳遞給包裝函數。C++中std :: bind的函數裝飾器0x
std::function<void (int)> foo = postbind<int>(service, handle);
這就像我得到的一樣。我想讓postbind對象自動推斷出類型。我試過創建一個對象生成器make_postbind(服務,句柄),但它無法自動推導出類型。
下面我寫了一個測試用例。編譯使用:G ++ -o postbind postbind.cpp -std =的C++ 0x -lboost_system
我想獲得該行:
std::function<void (int)> func = postbind<int>(strand, std::bind(foo, myfoo(), 'a', _1));
下到:
std::function<void (int)> func = postbind(strand, std::bind(foo, myfoo(), 'a', _1));
但我不確定如何。在我的代碼,我開始獲得正開始還真有些冗長postbind模板專門到eat up my horizontal whitespace :)
#include <boost/asio.hpp>
#include <thread>
#include <iostream>
#include <functional>
#include <memory>
using namespace boost::asio;
using std::shared_ptr;
typedef shared_ptr<io_service> service_ptr;
typedef shared_ptr<io_service::work> work_ptr;
typedef shared_ptr<io_service::strand> strand_ptr;
typedef std::shared_ptr<io_service::work> work_ptr;
using std::placeholders::_1;
template<typename... Args>
class postbind
{
public:
typedef std::function<void (Args...)> function;
postbind(strand_ptr strand, function memfunc)
: strand_(strand), memfunc_(memfunc)
{
}
void operator()(Args... params)
{
strand_->post(std::bind(memfunc_, std::forward<Args>(params)...));
}
private:
strand_ptr strand_;
function memfunc_;
};
// --------------------------------------------
struct myfoo
{
char a;
int b;
};
void run(service_ptr service)
{
service->run();
}
void foo(myfoo foo, char a, int x)
{
std::cout << "this thread: " << std::this_thread::get_id() << "\n"
<< x << "\n";
}
int main()
{
service_ptr service(new io_service);
strand_ptr strand(new io_service::strand(*service));
work_ptr work(new io_service::work(*service));
std::thread t(std::bind(run, service));
std::cout << "main thread: " << std::this_thread::get_id() << "\n";
std::function<void (int)> func = postbind<int>(strand, std::bind(foo, myfoo(), 'a', _1));
func(99);
t.join();
}
謝謝!