if the body consists of the single
return
statement,the return type is the type of the returned expression (after rvalue-to-lvalue,array-to-pointer,or function-to-pointer implicit conversion)
所以我认为这意味着一个lambda只能有一个return语句.但是为什么它仍然使用多个返回语句?
这个compiles在两个编译器上:
auto f = [] (bool c1,bool c2) { if (c1) return 1; if (c2) return 2; else return 3; };
@R_301_323@
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-seqoptreturn
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
.
所以返回类型只有在lambda表达式的全部只包含一个唯一的返回语句的情况下才被推导出来.在这种情况下,GCC和Clang都不符合标准,因为当且仅当两个返回语句导致不一致的扣除时,它们会发出错误消息.这是因为它们已经实现了C14标准,即使使用多个返回语句和/或多个其他语句也可以扣除返回类型. [expr.prim.lambda] / 4指定
The lambda return type is
auto
,which is replaced by the
trailing-return-type if provided and/or deduced fromreturn
statements as described in 7.1.6.4.
§7.1.6.4/ 9
If a function with a declared return type that contains a placeholder
type has multiplereturn
statements,the return type is deduced for
eachreturn
statement. If the type deduced is not the same in each deduction,the program is ill-formed.