Is it possible to code this path: while (lambda) {}

The code below was compiled without errors:

std::string lastName, chldName; while([&]() { return true; }) { //codes... } 

But when I tried this way:

 std::string lastName, chldName; while([&]() { std::cin >>lastName; return true; }) { //codes... } 

The compiler complained that:

error: cannot convert 'main () :: {(* and lastName)}' from 'main () ::' to 'bool'

How to understand this error? Can lambda be used this way?

+7
c ++ lambda c ++ 11
source share
3 answers

Your first example does not work the way you want, it is equivalent to while (true) , since the lambda will be converted to a function pointer, which will be converted to bool (true) - it should be

 while([&]() { return true; }()) 

Note for calling lambda

The second example will not compile without calling the lambda, since you are trying to access the bound variables, this prohibits the conversion from lambda to a function pointer, which can be converted to bool, but it will not be compiled with () ,

If the lambda expression does not include the return-return type, it looks like the return-return type indicates the following type:

- if the compound operator is of the form {expression-specifier-seqopt return expression; } the type of the returned expression after the conversion lvalue-to-rvalue (4.1), the conversion between arrays and pointers, sion (4.2) and the conversion of the function to a pointer (4.3);

- otherwise void.

In your case, the return type will be inferred to void , but since you are returning a bool, you should use trailing-return-type

 while([&]() -> bool { std::cin >>lastName; return true; }()) 
+10
source share

There is no need to explicitly express the return type, the problem is that you specify a while condition if the lambda function is its true, and not the value that it returns.

You really need a lambda call function in a loop state.

 while([] { return true; }()) { ///.... } 

EDIT

The reason the former are compiled and the latter is not because the former does not capture anything. The standard then allows you to convert it to a regular function pointer, which can be evaluated as bool (nullptr is false).

The second capture, which does not allow the compiler to convert it to a function pointer, and therefore not compiled.

+5
source share

Please note that in your code you are NOT a Lambda CALL .

 while([&]() { return true; }) 

Without a call, this is not a lambda return value, which is problematic.

A lambda that does not capture anything can be implicitly converted to a function pointer, which in turn can convert to bool .

The following compilation with g ++ 4.7.2, but not with Visual C ++ 12.0:

 int main() { if( [](){} ) {} } 

Below, where the lambda does the capture (and therefore cannot be converted), it does not compile with the compiler:

 int main() { int x; if( [&](){(void)x;} ) {} } 
+1
source share

All Articles