Sefa
Sefa

Reputation: 73

The lambda return type in C++

Lambda with function bodies that contain anything other than a single return statement that do not specify a return type return void.

via 《C++ Primer》 5th Edition, Page 389.

However, if we write the seemingly equivalent program using an if statement, our code won't 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 《C++ Primer》 5th Edition, Page 396.

I write 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 correctly run.

And then, I add some statements in Visual Studio:

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

As I move the cursor to the f, it shows me that the f's return type is int.

Why is this?

I am confused.

Upvotes: 7

Views: 3223

Answers (1)

hobbs
hobbs

Reputation: 240601

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

Upvotes: 10

Related Questions