我有一些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>'那么,最简单的解决方法是什么呢?
发布于 2011-01-05 21:03:52
需要手动指定返回类型:
boost::bind<void>(f)();
boost::bind<int>(f2, 13)();如果你不想显式地告诉bind,你也可以编写一个模板函数来自动推断返回类型,使用Boost.FunctionTypes来检查你的lambda的运算符()。
发布于 2011-01-05 17:59:28
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发布于 2011-01-05 18:05:59
我想你可能会对this MSDN forum post感兴趣。听起来这张海报和你的有同样的问题,并且在MS Connect上有一个bug。
https://stackoverflow.com/questions/4602568
复制相似问题