Tim*_*imo 16 c++ lambda visual-studio-2010 c++11
我有一些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>'
Run Code Online (Sandbox Code Playgroud)
那么,最简单的解决方法是什么?
ltj*_*jax 22
您需要手动指定返回类型:
boost::bind<void>(f)();
boost::bind<int>(f2, 13)();
Run Code Online (Sandbox Code Playgroud)
你也可以写自己的模板功能,自动将推断返回类型使用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
Run Code Online (Sandbox Code Playgroud)