Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple functions to for each algorithm

I would like to ask if it's possible to define for each algorithm (like in STL) that would take multiple functions as input arguments and evaluate them in left to right order?

template <typename Iterator, typename ... Args>
void for_each(Iterator begin, Iterator end, Args ... args) {
// apply functions passed in Args... to range [begin,end)
}

How would I access those functions passed by Args? Is it possible only with some template recursion?

like image 238
Alexander Bily Avatar asked Aug 28 '26 21:08

Alexander Bily


2 Answers

You can use something like this:

#include <iostream>
#include <utility>
#include <algorithm>

template <typename Iterator, typename F1>
void for_each(Iterator begin, Iterator end, F1 f1)
{
   std::for_each(begin, end, f1);
}

template <typename Iterator, typename F1, typename... Fun>
void for_each(Iterator begin, Iterator end, F1 f1, Fun... fs)
{
   std::for_each(begin, end, f1);
   for_each(begin, end, fs...);
}

int main()
{
    std::array<int, 5> a =  {1,2,3,4,5};

    auto f1 = [](int i){std::cout << "f1: " << i << " ";};
    auto f2 = [](int i){std::cout << "f2: " << i << " ";};

    for_each(a.begin(), a.end(), f1, f2);
}

output:

f1: 1 f1: 2 f1: 3 f1: 4 f1: 5 f2: 1 f2: 2 f2: 3 f2: 4 f2: 5 

live example

like image 197
m.s. Avatar answered Aug 30 '26 11:08

m.s.


You don't have to do some special template trickery for this, just define a recursion like below:

template <typename Iterator, typename F>
void recurse(Iterator first, Iterator last, F f) {
  if(first != last) {
    f(*(first++));
  }   
}

template <typename Iterator, typename F, typename ...Args>
void recurse(Iterator first, Iterator last, F f, Args ...args) {
  if(first != last) {
    f(*(first++));
    recurse(first, last, args...);
  }   
}

template <typename Iterator, typename ...Args>
void variadic_for_each(Iterator first, Iterator last, Args ...args) {
  recurse(first, last, args...); 
}

LIVE DEMO

like image 32
101010 Avatar answered Aug 30 '26 13:08

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!