Forget the templates. Use lambdas. Modern C++

In the previous post, I have presented variadic function template as an simple but effective print() function. It is perhaps “simple” looking but it requires non trivial modern C++ knowledge to code and to understand one.

Now forget the templates. 

Use lambdas.  And by using modern C++ we do not even need to spend time carefully coding variadic templates or even templates.

We can simply use lambdas. Modern C++ also deliver generic lambdas and with variable number of arguments too.

As simple as this. No hairy template declarations. if constexpr () is a C++17 “novelty”. It happens at compile time and thus if there are no arguments given to print() it will  compile to “nothing” on that call.

Same as previous template version this function is not recursive. Parameter pack is unpacked into a dummy array initializer list in an 1 … N orderly sequence. Comma operator you see in there does the std::cout call first and then just produces a single zero. It is a little trick (or not) and it is perfect.

Also embedding it in the  anonymous namespace makes the print() unique on the application level.

Enjoy …

Forget the templates. Use lambda.
Forget the templates. Use lambda.

Leave a Reply