Forget the templates. Use lambdas. Part 2

Just improved the print() lambda from the part one.

Allow me to analyze it for you  in a bit of a detail. First the code.

win::con::out is part of my windows console library. You can replace that call with your favorite set of overloads to process whatever you want to print, or simply just use std::cout

But. What is this return print , on the bottom?

Here we return the lambda from the same lambda in itself. Yes. That is possible. Compiles and works.  This gives me the CallStream pattern that I have discovered (using JavaScript) and was writing about sometimes ago. But this time it is in a modern C++:

This lambda by the way replaces the whole article full of non trivial C++98 code I had to write to do C++ implementation of the CallStream.

This also shows the power of the auto keyword. Without it it will be almost impossible to declare the type of the lambda in use or to declare and code fiddly template declarations for a generic template function  variant of this.

Instead we have extremely simple and extremely powerful idiom in extremely small amount of modern C++ code.

And the last interesting detail. Why is all of this in an anonymous namespace? Well this is not strictly related to CallStream in C++ but is yet another rather interesting idiom of modern C++. About which I shall write next time.

That is a lot of extremes for one post 🙂

So little C++ so much good!
So little C++ so much good!


Leave a Reply