Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

c++ - Compiler warning: lambda return type cannot be deduced

Consider this example:

#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 << '
';
}

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...