Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my book's discussion of lambda return types wrong?

My book says this:

Lambdas with function bodies that contain anything other than a single return statement that do not specify a return type return void.

but this:

auto f = []{
  int i=0; i++;
  return std::string("foo");
};
std::cout << f() << std::endl;

actually compiles and prints out "foo", but that lambda expr has more than just a single return statement so it should return void, because it does not manually specify "-> std::string" as a return type.

What's going on here?

I'm using Apple's compiler in the latest Xcode 4.6, based on Clang 3.2 it seems:

clang --version

Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn) Target: x86_64-apple-darwin12.2.0 Thread model: posix

like image 428
user2015453 Avatar asked Feb 06 '13 20:02

user2015453


People also ask

What is the return type of lambda?

The return type of a lambda expression is automatically deduced. You don't have to use the auto keyword unless you specify a trailing-return-type. The trailing-return-type resembles the return-type part of an ordinary function or member function.

Can C++ lambda return value?

Return Value A C++ lambda function executes a single expression in C++. A value may or may not be returned by this expression. It also returns function objects using a lambda.


1 Answers

The book accurately reflects the rules in draft n3290 of the Standard. Perhaps your compiler implemented a different draft.

In section 5.1.2p4, the draft reads

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-seqoptreturn expression ; } the type of the returned expression after lvalue-to-rvalue conversion, array-to-pointer conversion, and function-to-pointer conversion;
  • otherwise, void.

The syntactic construct attribute-specifier-seq may be alignas or the double-bracketed attributes. Not variable declarations.

Draft n3485, which followed publication of C++11 (i.e. it is work in progress toward C++1y), contains the same wording. I don't know if there was a different rule in some draft earlier than n3290.

like image 91
Ben Voigt Avatar answered Oct 02 '22 12:10

Ben Voigt