generating calls to lambdas with arbitrary number of parameters

  • A+

The following definition has proven to be very useful for me:

template<class Func, class... Args> void apply_on_each_args(Func f, Args... args) {     (f(args), ...); } 

Basically, the arguments pack folded on comma operator, allows to define several calls to a function taking an argument. For example:

apply_on_each_args([] (auto x) { cout << x << endl; }, 1, 2, "hello"); 

will call the anonymous lambda on 1, 2 and "hello".

That idea presented, I would like to do the same thing but passing lambdas taking two, three, and so on arguments. For example, something like that

apply_on_each_args([] (auto x, auto y) { // use x and y }, 1, 2, "hello",  "bye"); 

Any clue, technique, idea, etc that allow achieving it?


The best I can imagine (at the moment) is the good old recursive way.

By example

// ground case template <typename Func> void apply_on_each_2_args (Func)  { }  // recursive case template <typename Func, typename A0, typename A1, typename ... Args> void apply_on_each_2_args (Func f, A0 a0, A1 a1, Args ... args)  { f(a0, a1); apply_on_each_2_args(f, args...); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: