Compiler warning: lambda return type cannot be deduced

淺唱寂寞╮ 提交于 2019-11-29 11:20:37

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

§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.

[...]

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.

It is worth noting that this issue has been rectified in C++14. The language now correctly deduces the return type as the OP expected. From the draft standard [7.1.6.4.11]:

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed. Once a return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements. [ Example:

auto n = n; // error, n’s type is unknown
auto f();
void g() { &f; } // error, f’s return type is unknown
auto sum(int i) {
if (i == 1)
    return i; // sum’s return type is int
else
    return sum(i-1)+i; // OK, sum’s return type has been deduced
}

—end example ]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!