gpt4 book ai didi

c++ - 编译器警告 : lambda return type cannot be deduced

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:57 25 4
gpt4 key购买 nike

考虑这个例子:

#include <algorithm>
#include <iostream>

int main()
{
std::string str = "abcde4fghijk4l5mnopqrs6t8uvwxyz";
std::string str2;

std::remove_copy_if(str.begin(), str.end(),
std::back_inserter(str2),
[](char& c) {
if (std::isdigit(c))
return true; // <----- warning here
else
return false;
}
);

std::cout << str2 << '\n';
}

使用 GCC 4.6.1,这可以很好地编译并打印出预期的输出(字母表),但我收到一条警告说 “只有当 return 语句是函数体中的唯一语句时,才能推导出 lambda 返回类型” .

现在,我知道如何摆脱警告(使用尾随返回类型或简单地说 return isdigit(c);),但我很好奇,因为编译器不会警告什么都没有(或者应该是这样):像这样的代码可能会出什么问题?标准对此有任何说明吗?

最佳答案

正如@ildjarn 在他的评论中所说,根据标准,您的代码只是格式错误。

§5.1.2 [expr.prim.lambda] p4

[...] 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.

[...]

就是这样,基本上如果大括号内的代码(在标准中称为compund-statement)不是return some_expr;,标准说明了返回类型是不可推导的,你得到一个 void 返回类型。

关于c++ - 编译器警告 : lambda return type cannot be deduced,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8582610/

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