How to pass a lambda in a function with a capture?

Change

void DoSomething( void (*func)() )

to

void DoSomething( std::function<void()> func )

Your current parameter type void (*func)() is a function pointer, which is a type of callable (something that can be called like a function) that doesn't hold state. That is why your variable this can't be passed into the function.

Only lambdas that capture nothing can be converted to a stateless function pointer.

std::function however can represent (almost) anything callable. It could be a raw function, or an instance of a class that implements operator(), or it could be your lambda holding state.


An alternative is to simply use templates to avoid the potential overhead associated with large lambdas that need to be packaged by std::function.

#include <functional>

using namespace std;

template<typename Callable> 
void DoSomething(Callable c) { c(); }  // calls the lambda with no args

int main() 
{   
     DoSomething([]{ printf("Hello\n"); });   
     DoSomething([msg = "World"] { printf("%s\n", msg); });
}

Live Code: http://goo.gl/LMvm3a

Tags:

C++

Lambda