编译器警告:无法推断lambda返回类型 [英] Compiler warning: lambda return type cannot be deduced

查看:89
本文介绍了编译器警告:无法推断lambda返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

#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返回类型。

With GCC 4.6.1, this compiles fine and prints expected output (the alphabet) but I get a warning saying "lambda return type can only be deduced when the return statement is the only statement in the function body".

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

Now, I know how to get rid of the warning (using trailing return type or simply saying return isdigit(c);), but I'm curious, since compiler doesn't warn for nothing (or so it should be): what could possibly go wrong in code like this? Does standard say anything about it?

推荐答案

正如@ildjarn在其评论中所说,根据代码,您的代码只是格式不正确

As @ildjarn says in his comment, your code is simply ill-formed according to the standard.

§5.1.2[expr.prim.lambda] p4


[...]如果 lambda表达式不包含 trailing-return-type ,则为就像 trailing-return-type 表示以下类型一样:

[...] If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:


  • 如果 compound-statement 的格式为

    { attribute-specifier-seq opt return expression }

    左值到右值转换(4.1),数组到指针转换
    (4.2 ),以及函数到指针的转换(4.3);

  • 否则, void

  • 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 返回类型。

That's it, basically if the code inside the curly brackets (called compund-statement in the standard) is anything but return some_expr;, the standard says the return type is undeducible and you get a void return type.

这篇关于编译器警告:无法推断lambda返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆