I recently stumbled upon this example code and I was confused:
auto named_funct(const MyClass& some_class)
{
return [some_class](const MyClass2& some_other_class)
{
return some_class <= some_other_class; // some expression between capture and input parameter to the Lambda
};
}
Is there any reason at all to wrap an anonymous function in a named function? It seems like an extra function call stack is being created for no reason.
named_funct
doesn't execute the lambda, it returns it. You could use it like this:
auto it = std::find_if(std::begin(some_vector), std::end(some_vector),
named_funct(some_instance));
The odd thing is that named_funct
takes a parameter that it doesn't do anything with, unless you have a copy/paste error (another instance is passed to the actual lambda). This example is also so trivial I don't see the benefit of a lambda, but if named_funct
's argument was captured and used somehow, this is a useful pattern.
There can be a reason (if, for example, you want partial functions (the ability to do f(x)(y) rather than f(x, y))), but there isn't here. The outer input argument is shadowed by the argument of the anonymous function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With