繁体   English   中英

如何在VC ++ 2010中使用带有boost :: bind / std :: bind的lambda函数?

[英]How to use lambda functions with boost::bind/std::bind in VC++ 2010?

我有一些lambda函数,我想用boost :: bind或std :: bind绑定。 (不管哪一个,只要它有效。)不幸的是它们都给了我不同的编译器错误:

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自动推断返回类型,以检查lambda的operator(),如果您不想明确告诉bind。

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

我想你可能对这篇MSDN论坛帖子感兴趣。 听起来这张海报与你的问题有同样的问题,并向MS Connect提出了一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM