Consider a function to compare positive integers; the function itself uses a lambda to do the job ..
// Pass n1, n2 by value to the lambda.
bool Compare(int n1, int n2) {
return [](int n1, int n2) { return n1 > n2; };
}
The above snippet compiles fine; though Compare() always returns true;
However, the following code even fails to compile -
// capturing values
bool Compare(int n1, int n2) {
return [n1, n2]() -> bool { return n1 > n2; };
}
and returns the error
lambda.cpp:48:46: error: cannot convert 'Compare(int, int)::__lambda2' to 'bool' in return
return [n1, n2]() -> bool { return n1 > n2; };
Question
May be these are not the intended use of introducing lambda's in C++, still...
You can pass lambda expressions as arguments to a function. If you have to pass a lambda expression as a parameter, the parameter type should be able to hold it. If you pass an integer as an argument to a function, you must have an int or Integer parameter.
Capture clauseA lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.
Creating a Lambda Expression in C++ auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.
The [=] you're referring to is part of the capture list for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created.
Why the first one always returns true?
Lambdas decay into function pointers, which are implicitly convertible to booleans (always true
for lambdas because the pointer is never null).
Why second fails to compile?
Lambdas that capture anything do not have this conversion to a function pointer (how would that state get through?)
If you must use a lambda:
Call it:
return [](int n1, int n2) { return n1 > n2; }(n1, n2); //notice the () to call it
Or, your second way, which makes more sense, but not as much as just return n1 > n2
:
return [=] { return n1 > n2; }(); //= captures everything used by value
//-> bool and parameter list are redundant
Finally, it's worth noting that std::greater
, in <functional>
, already does this:
std::sort(…, std::greater<int>()); //std::greater<> in C++14
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