Question

([] () -> decltype(std::cout << "Hello") {
    return std::cout << "Hello";
}()) << ", world!";

prints Hello, world!.

I simply don't understand what's going on here. Can someone explain it to me in simple terms?

Was it helpful?

Solution

([] () -> decltype(std::cout << "Hello")

This creates a lambda (in-place function) with the same return type that the expression std::cout << "Hello" has - that's std::ostream&. The [] starts the lambda, the () is an empty parameter list, the -> preceeds the return type, and decltype(X) is equivalent to the type of the expression X. Then the function body:

{
    return std::cout << "Hello";
}

Then the function is called... that outputs "Hello" and returns the stream....

 ())

And finally, to the returned stream, a little more text is sent...

 << ", world!";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top