Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have some lambda functions which I want to bind using either boost::bind or std::bind. (Don't care which one, as long as it works.) Unfortunately both of them give me different compiler erros:

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>'

So, what is the simplest workaround for this?

like image 948
Timo Avatar asked Jan 05 '11 09:01

Timo


People also ask

What does boost:: bind do?

boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.

What is_ 1 in boost:: bind?

_1 is a placeholder. Boost. Bind defines placeholders from _1 to _9 . These placeholders tell boost::bind() to return a function object that expects as many parameters as the placeholder with the greatest number.

What is the use of std :: bind?

std::bind is a Standard Function Objects that acts as a Functional Adaptor i.e. it takes a function as input and returns a new function Object as an output with with one or more of the arguments of passed function bound or rearranged.

What does bind function do in C++?

std::bind. Returns a function object based on fn , but with its arguments bound to args . Each argument may either be bound to a value or be a placeholder: - If bound to a value, calling the returned function object will always use that value as argument.


1 Answers

You need to manually specify the return type:

boost::bind<void>(f)();
boost::bind<int>(f2, 13)();

You can also write yourself a template-function to deduce the return type automagically using Boost.FunctionTypes to inspect your lambda's operator(), if you don't like to explicitly tell bind.

like image 83
ltjax Avatar answered Sep 28 '22 16:09

ltjax