需要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();
}
谢谢!