1

Presuming i would use Lamdba functions to define fuctions within functions to better structure the code, in what cases someone could prefer the second option over the first one, as the latter is clearly less reusable since no different arguements can be passed?

int main() {
    int foo = 1;
    int bar = 4;

    //Passing as Parameters
    auto add = [](auto a, auto b) {
        return a + b;
    };
    std::cout << "Add: " << add(foo, bar) << std::endl;

    //Capturing by value
    auto multiply = [=]() {
        return foo * bar;
    };
    std::cout << "Multiply: " << multiply() << std::endl;

    return 0;
}
Beltway
  • 508
  • 4
  • 17
  • The second lambda expects no arguments and the first expects two arguments. You could pass the lambda as callback to another function and the other function calls the lambda with given values, e.g. std::copy_if expects a function with one parameter. – Thomas Sablik Dec 04 '19 at 13:24
  • 1
    I'd argue against making `add` a lambda in the first place, it should be a normal function which makes it even more reusable as it can be used from other functions. – Alan Birtles Dec 04 '19 at 13:30
  • Defining functions within functions for the sake of it is not really what lambdas are for: If C++ wanted to allow defining functions within functions, we could do that without lambdas. In particular, your example/argument is about a pure function (one with no state), whereas the most significant benefit of lambdas is allowing the convenient capture of state into a (stateful) functor. It should be no surprise that capturing state is not useful for writing your state-free functions. You can still use lambdas for that, but don't expect all of their design aspects to be relevant/useful... – Max Langhof Dec 04 '19 at 13:35

2 Answers2

3

Capturing by value stores the values directly in the lambda. These values are accessible in all invocations of that lambda.

If your lambda takes arguments then the values must be supplied each time.

This allows you to pass the lambda to things that don't allow passing arguments, or pass a different number of arguments. For example, you could pass a lambda with captured variables to std::for_each, and have the lambda operate on the captured values and the supplied element:

std::vector<int> vi={1,2,3,4,452,99};

auto x=56;

std::for_each(vi.begin(),vi.end(),[=](int i){
  std::cout<<x+i<<std::endl;
});
Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
0

When the function is passed to another function, such as a Standard Library algorithm which requires the function to have parameters.

QuentinUK
  • 2,997
  • 21
  • 20