Lambda return type in C ++

A lambda with function bodies that contain anything but one return, which does not indicate the return type return return.

via the “C ++ Primer” 5th Edition, page 389.

However, if we write a seemingly equivalent program using if, our code will not compile:

//error: can't deduce the return type for the lambda. transform(vi.begin(), vi.end(), vi.begin(), [](int i) { if(i < 0) return -i; else return i; } ); 

via the “C ++ Primer” 5th Edition, Page 396.

I am writing a program in Visual Studio:

 #include <iostream> #include <algorithm> #include <vector> using namespace std; int main(void) { vector<int> vi{ 1, -2, 3, -4, 5, -6 }; /* Is the return type void? */ transform(vi.begin(), vi.end(), vi.begin(), [](int i) { if (i < 0) return -i; else return i; }); for (int i : vi) cout << i << " "; cout << endl; system("pause"); return 0; } 

But it can work correctly.

And then I will add some statements in Visual Studio:

 auto f = [](int i) { if (i < 0) return -i; else return i; }; 

When I move the cursor to f, it shows me that the return type of f is int.

Why is this?

I am embarrassed.

+6
source share
1 answer

C ++ Primer 5th Edition covers C ++ 11, and in C ++ 11, the statement you quote is true. However, C ++ 14 supports the return of return types in more situations , including when a lambda has several return statements, if they all return the same type. Presumably your version of Visual Studio supports C ++ 14, or at least this feature.

+9
source

Source: https://habr.com/ru/post/1011599/


All Articles