我一直在编写代码,最近我发现 g++ 不会就某一类问题向我发出警告:根据 C++11 5.1.2.4,如果您的 lambda 不是单个 return 语句,则返回类型必须声明为 trailing-return-type 或为 void。
虽然 g++ 在足够合理的情况下被允许编译无效代码,但有没有办法关闭此行为(允许在 g++-4.7 中使用 -fpedantic
)或至少警告它?
示例代码:
[]() { return 0; } //is fine
[&a]() { a++; return 0; } //is not fine but g++ doesn't warn me
[&a]() -> int {a++; return 0; } //is fine again
C++11 5.1.2.4
An implementation shall not add members of rvalue reference type to the closure type. If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). 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-seq(opt) 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.
最佳答案
那是因为它是标准中的一个缺陷,并且会被更改(参见 DR 975 ):
975 Restrictions on return type deduction for lambdas
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.
我怀疑是否有办法将其关闭。
关于c++ - 多语句 lambda 的返回类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14450608/