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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/* forget templates, variadic generic lambda saves you of declaring them */ namespace dbj { inline auto print = [](auto && ... param) { if constexpr (sizeof...(param) > 0) { // C++17 fold-ing (std::cout << ... << param); } }; } // dbj |
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 with the great help of C++17 folding.
Also embedding it in the namespace, in some header, makes the inline print()
unique on the application level.
Enjoy …