Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to wrap a Lambda in a named function?

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.

like image 851
Seth Avatar asked Aug 08 '20 23:08

Seth


2 Answers

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.

like image 64
Stephen Newell Avatar answered Nov 14 '22 21:11

Stephen Newell


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.

like image 42
Fady Adal Avatar answered Nov 14 '22 21:11

Fady Adal