tags:

views:

186

answers:

2

I read on the internet many tutorials that explained how to use lambdas with the standard library (such as std::find), and they all were very interesting, but I couldn't find any that explained how I can use a lambda for my own functions.

For example:

int main()
{
    int test = 5;
    LambdaTest([&](int a) { test += a; });

    return EXIT_SUCCESS;
}

How should I declare LambdaTest? What's the type of its first argument? And then, how can I call the anonymous function passing to it - for example - "10" as its argument?

+14  A: 

Given that you probably also want to accept function pointers and function objects in addition to lambdas, you'll probably want to use templates to accept any argument with an operator(). This is what the std-functions like find do. It would look like this:

template<typename Func>
void LambdaTest(Func f) {
    f(10);
}

Note that this definition doesn't use any c++0x features, so it's completely backwards-compatible. It's only the call to the function using lambda expressions that's c++0x-specific.

sepp2k
This is the best answer.
DeadMG
In case of errors the error messages will be difficult to understand.
liori
It depends whether it's the best. This uses a template, and the other doesn't. This means that the function can't be virtual anymore and can't be defined separately in the cpp file. `std::function` is perfectly able to take function object class types too, albeit is a little slower when calling. But that difference is negligible for the very most applications :)
Johannes Schaub - litb
+10  A: 

If you don't want to template everything, you can do the following:

void LambdaTest (const std::function <void (int)>& f)
{
    ...
}
doublep
This syntax actually allows me to save the function variable to call it later, right? For example I wanted to implement a function that allowed to execute asynchronous database queries, where the lambda acts as a callback. (Of course I wouldn't be able to access closures by reference)
Andreas Bonini
Isn't it more idiomatic to pass functions by value?
FredOverflow
@Andreas Bonini: Yes, if you save to `std::function` (not a reference), you make a copy of `f`. However, I'm not sure how lambda/closures handle references when the object referred to goes out of scope, probably UB.@FredOverflow: My understanding is that `std::function` is not a trivial object, especially when wrapping lambdas. It is probably better to reference it to avoid unnecessary copying.
doublep
If your lambda captures the stack by value then yes the lambda can outlive those variables and will continue to keep copies of them. If it captures by reference you will have a problem.
Kate Gregory