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:
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.
source share