简体   繁体   中英

C++11 lambda expression - Capture vs Argument Passing

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...

  1. Why the first one always returns true?
  2. Why second fails to compile?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM