Justin G
Justin G

Reputation: 796

C++11 Multiline lambdas can deduce intrinsic types?

I use C++11 lambdas quite a lot, and I've often run into compile errors on multiline lambdas because I forgot to add the return type, as is expected, but I recently ran into one example that doesn't have this issue. It looks something like this:

auto testLambda = [](bool arg1, bool arg2)
{
    if (arg1)
    {
        if (!arg2)
        {
            return false;
        }

        return true;
    }

    return false;
};

This compiles just fine even though there's no return type specified. Is this just Visual Studio being dumb and allowing something it shouldn't, or can lambdas just always deduce intrinsic types?

I tried this with return values of all ints or floating point values and it also compiled just fine. I just found this to be really surprising so I wanted to be absolutely sure how it works before I start making assumptions and omitting return types that might break later on.

Upvotes: 0

Views: 100

Answers (1)

Brian Rodriguez
Brian Rodriguez

Reputation: 4359

Lambdas follow the same template deduction rules as auto-returning functions:

Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.

For auto-returning functions, the parameter P is obtained as follows: in T, the declared return type of the function that includes auto, every occurrence of auto is replaced with an imaginary type template parameter U. The argument A is the expression of the return statement, and if the return statement has no operand, A is void(). After deduction of U from P and A following the rules described above, the deduced U is substituted into T to get the actual return type:

auto f() { return 42; } // P = auto, A = 42:
                    // deduced U = int, the return type of f is int

If such function has multiple return statements, the deduction is performed for each return statement. All the resulting types must be the same and become the actual return type.

If such function has no return statement, A is void() when deducing.

Note: the meaning of decltype(auto) placeholder in variable and function declarations does not use template argument deduction.

Upvotes: 3

Related Questions