gpt4 book ai didi

c++ - 我们什么时候可以省略 C++11 lambda 中的返回类型?

转载 作者:IT老高 更新时间:2023-10-28 22:58:51 24 4
gpt4 key购买 nike

就我而言know ,在标准 C++11(不是 C++14)中,当省略 lambda 的返回类型时,其返回类型推导为:

  1. 返回表达式的类型,只要 lambda 只包含带有表达式的单个 return 语句,或者
  2. void 在所有其他情况下。

现在考虑这段代码:

#include <iostream>

auto closure = [](int x)
{
x++;
return x;
};

int main()
{
int y = closure(10);
std::cout << y << std::endl;
}

这应该属于情况 2.,但是在 g++4.9.2、g++5 和 clang++ 中,代码编译就像是带有 auto 类型推导的 C++14,使用 -pedantic -Wall -Wextra -std=c++11。这里发生了什么?我是不是对标准的解释错了?

最佳答案

您的代码在没有任何警告的情况下被接受,因为原始 C++11 限制被认为是标准中的缺陷,它允许实现修复该行为。见 CWG DR975 , DR1048N3638 .

975. Restrictions on return type deduction for lambdas

[Moved to DR status at the April, 2013 meeting as part of paper N3638.]

There does not appear to be any technical difficulty that would require the current restriction that the return type of a lambda can be deduced only if the body of the lambda consists of a single return statement. In particular, multiple return statements could be permitted if they all return the same type.

1048. auto deduction and lambda return type deduction.

...

Notes from the November, 2014 meeting:

CWG agreed that the change embodied in paper N3638 should be considered to have been a DR against C++11.

综上所述,DR975 建议修改 lambda 表达式的返回类型推导规则,以允许多个返回语句。

DR1048 发现了一个差异,即使用占位符类型 auto 推断正常函数的返回类型的规则与 DR975 中提出的规则略有不同。具体来说,普通函数的返回类型推导将在所有情况下丢弃顶级 cv 限定符,而 lambda 表达式的返回类型推导将保留类类型的 cv 限定符。

N3638 解决了这个问题。


我怀疑除了在上述 DR 实现之前找到一个支持 C++11 lambda 支持的编译器版本之外,还有什么方法可以恢复到原始行为。

关于c++ - 我们什么时候可以省略 C++11 lambda 中的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955478/

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