Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a lambda function?

Tags:

c++

c++11

lambda

For example, I can define a lambda function as

auto f = [](double value) {double ratio = 100; return value * ratio;}

Now I want to generate a function with the ratio an argument and return the lambda function like

auto makeLambda(double ratio) { return [=](double value) {return value * ratio;}; }

How to do it?

like image 640
user1899020 Avatar asked Jun 26 '14 13:06

user1899020


People also ask

How do I return AWS lambda value?

Returning a valueIf you use the RequestResponse invocation type, such as Synchronous invocation, AWS Lambda returns the result of the Python function call to the client invoking the Lambda function (in the HTTP response to the invocation request, serialized into JSON).

What is the return type of lambda function?

The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.

Can lambdas return?

Returning a value from a lambda expressionYou can explicitly return a value from the lambda using the qualified return syntax. Otherwise, the value of the last expression is implicitly returned.

Can lambda statements return a value?

The lambda must contain the same number of parameters as the delegate type. Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter. The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.


1 Answers

With C++14 function return type deduction, that should work.

In C++11, you could define another lambda (which can deduce the return type), rather than a function (which can't):

auto makeLambda = [](double ratio) {
    return [=](double value) {return value * ratio;};
};

As noted in the comments, this could be further wrapped, if you particularly want a function:

auto makeLambdaFn(double ratio) -> decltype(makeLambda(ratio)) {
    return makeLambda(ratio);
}
like image 133
Mike Seymour Avatar answered Sep 18 '22 21:09

Mike Seymour