c++c++17callablevariadic

C++17: pass multiple callable objects together with their parameters


I would like to write a function (C++17 if that matters) that accepts multiple callable objects together with their arguments and executes them in a loop. I would also like to avoid any intermediate copying of data.

Example:

Assume we have three functions f0, f1 and f2 that expect different number of input parameters

void f0() {
 // Implementation of f0
}
void f1(int a) { 
 // Implementation of f1
}
void f2(int a, int b) {
 // Implementation of f2
}

I'm looking for a way to pass all functions above together with sample input arguments into class or another function (say Execute). A sample interface would look like following:

int main() {
  // If Execute is a class
  Execute exec({f0}, {f1, 4}, {f2, 1, 2});

  // The result of the command above is a sequence of calls
  // 1. f0()
  // 2. f1(4)
  // 3. f2(1, 2)
}

I would like to avoid any intermediate copying of data.

So my question how would one achieve that?


Solution

  • For completeness, here's a zero effort solution.

    template <typename... T> 
    void execute (T&&... t)
    {
        (t(),...);
    }
    
    int main()
    {
        int a = 42, b = 0;
        // this
        execute([&](){f0();}, [&](){f1(a);}, [&](){f2(a,b);});
        // or this
        execute(std::bind(f0), std::bind(f1, a), std::bind(f2, a, b));
    }