c++ how to handle two param packs — lambda solution

The requirement is to be able to handle two-parameter packs in the same time.  Just to be sure we are on the same page, using one parameter pack call, on a single c++ function, looks like this:

 

A number of arguments on the same variadic function are unspecified and arguments can be of various unrelated types.  Good old printf() is the most famous example,  in existence from the primordial days of C.

A bit easier to declare and code in standard C++ but nothing new.

So, how do we implement this requirement? Two param packs in the same time? Many have tried, There are few complex class-based solutions.

The Concept

Let us imagine we have to merge two ad-hoc param pack sets.  The legacy way would probably be to encapsulate the solution in a class and use it like this:

Above is not lambda calculus a.k.a. functional programming. And. It is not very elegant.

Lambda based solution in use looks like this:

And, of course, under different requirements, this same concept, will also serve the purpose.

Looks suspiciously like “metacall“. This is because it is. But simpler. It’s only purpose is to receive two param packs “in one go”. And do something with two of them. And optionally return something.

Lambda, the C++ core language feature, allows for simple, elegant and effective solutions. This is one of them.

The Solution

For tuple printing, I use the variant of this.

Same as ever I tend to avoid, what I am calling “pathologically generic” solution. Thus preserving the simplicity lambda is giving me.

The return type is obviously completely arbitrary.  The point is in the feasibility of this solution when compared to the usual ones.

And simplicity is resilience. And resilience is feasibility.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.