Pass lambda with parameter

I would like to pass the lambda to funciton.

it

boost::function<void()> fncPtr(boost::bind<void>([](){/* something */})); 

works, but if lambda had a parameter, I don't know how to do it correctly:

 boost::function<void(bool)> fncPtr(boost::bind<void,bool>([](bool){/* something */}, _1)); 

does not work.

Where am I mistaken? How to pass lambda with arguments?

I would like to do this in a member function. So, in the β€œglobal scope” (is that the name?), This method works fine above.

+4
source share
3 answers

You probably have a problem with the compiler. I also have a bug in Visual Studio 2010. You can help the compiler convert the lambda to a function using a helper function:

 template <typename T> void closureToFunction(bool x){ T f; return f(x); } int main() { auto exp = [](bool x){/* something */}; boost::function<void(bool)> fncPtr( boost::bind( closureToFunction<decltype(exp)>, _1) ); return 0; } 
0
source

This works fine for me with GCC4.5:

 #include <boost/bind.hpp> #include <boost/function.hpp> int main() { boost::function<void(bool)> fncPtr(boost::bind<void>([](bool){/* something */}, _1)); } 

It does not need a parameter type. These types of parameters can be templates in any case (for some functors), therefore, in general, it cannot depend on them. He needs only a return type.

By the way, this even works for me when I go through <void, bool> , but only when lambdas don't have captures. I think this might work for me, because GCC4.5 supports lambdas conversion to work with pointer types when lambdas does not have a capture condition. <void, bool> will do a bind on the candidate, which will take a pointer to a function, and do a lambda conversion to this. Your compiler apparently does not yet support this special conversion (but this requires FDIS).

So, just go through only <void> and it should work.

+3
source

I have summed up some methods here on Ideone . Notice that I used C ++ 0x versions, Boost should work fine too.
It really depends on what your function wants as a parameter. If it is just obscured by a template or takes (std::|boost::)function , then it will make a simple lambda. There is no need for complex binding or packaging in an additional (std::|boost::)function .

+2
source

All Articles