gpt4 book ai didi

C++11 对 lambda 返回类型的限制

转载 作者:可可西里 更新时间:2023-11-01 15:48:38 24 4
gpt4 key购买 nike

我正在阅读 cppreference关于如何推导出 C++11 lambda 的返回类型:

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 语句。但为什么它仍然适用于多个 return 语句?

compiles在两个编译器上:

auto f = [] (bool c1, bool c2) {
if (c1) return 1;
if (c2) return 2;
else return 3;
};

最佳答案

这有点不精确。 [expr.prim.lambda]/4:

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 表达式的整个主体仅由一个单独的 return 语句组成时,才能推导出返回类型。

GCC 和 Clang 都不符合标准这种情况下,当且仅当两个 return 语句导致不一致的推论时,他们才会发出错误消息。这是因为他们已经实现了 C++14 标准,即使存在多个 return 语句和/或多个其他语句,该标准也会扣除返回类型。 [expr.prim.lambda]/4 指定

The lambda return type is auto, which is replaced by the trailing-return-type if provided and/or deduced from return 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 multiple return statements, the return type is deduced for each return statement. If the type deduced is not the same in each deduction, the program is ill-formed.

关于C++11 对 lambda 返回类型的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26692637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com