Lambda return type

Hi guys,

Here,
https://stackoverflow.com/questions/9620098/explicit-return-type-of-lambda

I read that:

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.


OK, clear as a crystal but why on this MSDN site they write this

1
2
3
4
    auto t = create_task([]() -> int
    {
        return 42;
    });


Why does the Microsoft overcomplicate samples? Doesn't it? Maybe I'm wrong or I just don't get it, but it should be without

 
-> int


exact one statement ✔
returns an expression ✔
Last edited on
In this case the -> int is redundant, but not necessarily without purpose. For someone casually reading the code it helps make it clear that the intent is for the lambda to return an int. Consider this:
1
2
3
4
    auto t = create_task([]()
    {
        return foo();
    });
Without the explicit type and without looking up what foo() is, you can't tell what this lambda returns.
Last edited on
Here,
https://stackoverflow.com/questions/9620098/explicit-return-type-of-lambda
I read that:
. . .
exact one statement
returns an expression

You’ve already got your answer, but let me add that post is dated 2012-03-08.
Here:
http://en.cppreference.com/w/cpp/language/lambda
it says:
[since C++14] The return type is deduced from return statements as if for a function whose return type is declared auto.

Since C++14 lambda return types can be deduced by the compiler regardless how many statements are there in the function.
Registered users can post here. Sign in or register to post.