Question

I've been writing code, and I've recently found out that g++ doesn't warn me about a certain class of issue: per C++11 5.1.2.4, if your lambda is not a single return statement then the return type must be declared as a trailing-return-type or be void.

Although g++ is allowed to compile invalid code if it makes enough sense, is there a way to either turn this behavior off (allowed with -fpedantic in g++-4.7) or all least warn about it?

Example code:

[]() { 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.

Was it helpful?

Solution

That is because it is a defect in the standard, and will be changed (see 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.

I doubt if there is a way to turn it off.

OTHER TIPS

GCC 4.8.1 (and possibly earlier) and clang 3.3 already implements it; fixing DR975.

There is now a proposal (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3386.html) to get it into C++1y

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top