如何在VC++ 2010中使用boost :: bind/std :: bind使用lambda函数?
问题描述:
我有一些lambda函数,我想用boost :: bind或std :: bind绑定。 (不关心哪一个,只要它的作品。)不幸的是他们两个给我不同的编译器错误回报:如何在VC++ 2010中使用boost :: bind/std :: bind使用lambda函数?
auto f = [](){ cout<<"f()"<<endl; };
auto f2 = [](int x){ cout<<"f2() x="<<x<<endl; };
std::bind(f)(); //ok
std::bind(f2, 13)(); //error C2903: 'result' : symbol is neither a class template nor a function template
boost::bind(f)(); //error C2039: 'result_type' : is not a member of '`anonymous-namespace'::<lambda0>'
boost::bind(f2, 13)(); //error C2039: 'result_type' : is not a member of '`anonymous-namespace'::<lambda1>'
那么,什么是这个最简单的解决方法吗?
答
您需要手动指定返回类型:
boost::bind<void>(f)();
boost::bind<int>(f2, 13)();
你也可以写自己的模板功能,自动将推断返回类型使用Boost.FunctionTypes检查你的拉姆达的运营商(),如果你不不想明确地告诉绑定。
答
std::function<void()> f1 = [](){ std::cout<<"f1()"<<std::endl; };
std::function<void (int)> f2 = [](int x){ std::cout<<"f2() x="<<x<<std::endl; };
boost::function<void()> f3 = [](){ std::cout<<"f3()"<<std::endl; };
boost::function<void (int)> f4 = [](int x){ std::cout<<"f4() x="<<x<<std::endl; };
//do you still wanna bind?
std::bind(f1)(); //ok
std::bind(f2, 13)(); //ok
std::bind(f3)(); //ok
std::bind(f4, 13)(); //ok
//do you still wanna bind?
boost::bind(f1)(); //ok
boost::bind(f2, 13)(); //ok
boost::bind(f3)(); //ok
boost::bind(f4, 13)(); //ok
你为什么要使用绑定?你不能只调用f()或f2(1)? – Jagannath 2011-01-05 09:54:23
@Jagannath:这当然只是一个简单的例子,但实际上我想将绑定结果存储到函数对象中。 – Timo 2011-01-05 09:58:29
你为什么要使用绑定?我认为C++ 0x提供了闭包? – 2011-01-05 10:09:34