nightlytrails
nightlytrails

Reputation: 2662

Why is a captureless lambda always true when converted to bool, and why is this not the case for a lambda with captures?

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?

Upvotes: 11

Views: 1880

Answers (1)

Qaz
Qaz

Reputation: 61910

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

Upvotes: 18

Related Questions