I’ve been reading up on lambdas, and I am wondering why it would be advantageous to explicitly capture a variable, either by value or by reference, rather than pass it to a lambda via the arguments.
I can imagine if there was a large list of variables outside the scope of a lambda that one would want to use. Not having to write out the arguments for them all by using [=]
/[&]
saves some typing. but I can’t imagine a use-case for writing a lambda to handle complex logic requiring that many variables in the surrounding scope anyway.
And, for cases with a small capture list, what have you saved/accomplished by using a capture rather than an argument besides the tiniest bit of typing:
#include <iostream>
int main() {
int N = 2;
auto less_than = [](int x, int y){ return x < y; };
auto less_than_N = [N](int x) { return x < N; };
bool result1 = less_than(4, N);
bool result2 = less_than_N(4);
std::cout << result1 << std::endl;
std::cout << result2 << std::endl;
return 0;
}
Essentially, I’d like to know how captures are useful in a more general sense. I know how to use them, but not the cases in which they become useful for real world purposes. My experience using lambdas stems from wanting to quickly create a function “object” so that it can be passed to another method or function, or maybe stored in a map for look up later. I’m not seeing how captures help much in that context.
9