Explain this code with decltype in it

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

prints Hello, world! .

I just don’t understand what is going on here. Can someone explain this to me in simple words?

+4
source share
1 answer
 ([] () -> decltype(std::cout << "Hello") 

This creates a lambda (function in place) with the same type of return expression as the expression std::cout << "Hello" has - this is std::ostream& . [] starts the lambda, () represents an empty list of parameters, -> pursues the return type, and decltype(X) equivalent to the type of the expression X. Then the body of the function:

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

Then a function is called ... that prints "Hello" and returns a stream ....

  ()) 

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

  << ", world!"; 
+6
source

Source: https://habr.com/ru/post/1481856/


All Articles