When can we omit the return type in a C++11 lambda?

前端 未结 3 794
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 00:02

As far as I know, in standard C++11 (not C++14), when omitting the return type of a lambda, its return type is deduced to be:

  1. The type of the
3条回答
  •  一生所求
    2020-12-02 00:24

    This is what I find in the C++ Draft Standard N3337:

    If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:

    — if the compound-statement is of the form

    { attribute-specifier-seqopt return expression ; }

    the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);

    — otherwise, void.

    [ Example:

    auto x1 = [](int i){ return i; }; // OK: return type is int
    auto x2 = []{ return { 1, 2 }; }; // error: the return type is void (a
                                      // braced-init-list is not an expression)
    

    end example ]

    The standard seems to indicate that:

    • When only one statement is present, and
    • It is a return statement, and
    • The object being returned is an expression

    Then the return type is deduced from the expression. Otherwise the return type is void.

提交回复
热议问题