如何在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>' 

那么,什么是这个最简单的解决方法吗?

+0

你为什么要使用绑定?你不能只调用f()或f2(1)? – Jagannath 2011-01-05 09:54:23

+3

@Jagannath:这当然只是一个简单的例子,但实际上我想将绑定结果存储到函数对象中。 – Timo 2011-01-05 09:58:29

+0

你为什么要使用绑定?我认为C++ 0x提供了闭包? – 2011-01-05 10:09:34

您需要手动指定返回类型:

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 
+0

只有'函数'引入了运行时间接法,'bind'更快......是吗? – Dario 2011-01-05 10:21:55

+0

我怀疑调用由绑定产生的仿函数会更快,因为绑定结果在大多数情况下增加了另一个间接层次。在需要绑定某些参数的情况下,可能需要绑定。在上面的例子中std :: bind(f2,13)();将第一个参数绑定到常量值13.绑定的结果是一个“函子”,它不带参数并返回void。 – ds27680 2011-01-05 10:46:45

+0

调用'bind'的结果可能会稍微快一点,因为没有像函数那样通过虚函数调用。 – ltjax 2011-01-05 13:26:02

我想你可能会感兴趣的this MSDN forum post。 听起来像海报有同样的问题,并提出了MS Connect的错误。