C++ How to store parameter expansion pack for future invocation

Viewed 262

I have the following:

template<typename F, typename... Args>
void Enqueue(F&& f, Args&&... args)
{
    f(args...); // want to assign this to a variable and insert into queue/vector
}

I want to store f and args (expanded or not) in a vector such that later on I can retrieve and call f(args). Does c++ supports a way to packaging it?

1 Answers

You can write a class like this:

struct Fs {

 std::vector<std::function<void()>> v;  // stores the functions and arguments
                                        // as zero argument lambdas

 template<typename F, typename... Args>
 void Enqueue(F&& f, Args&&... args)
 {
    v.push_back([=] { f(args...); });  // add function and arguments
                                       // as zero argument lambdas
                                       // that capture the function and arguments
 }

 void CallAll() 
 {
   for (auto f : v)
     f();                              // calls all the functions
 }
};

and then use it like this:

int add(int a, int b, int c) { std::cout << "add"; return a + b + c; }
int subtract(int a, int b) { std::cout << "sub"; return a - b; }

int main(){

  Fs fs;

  fs.Enqueue(add, 1, 3, 5);
  fs.Enqueue(subtract, 5, 4);
  fs.Enqueue([](int a) { std::cout << a; }, 4);

  fs.CallAll();
 
}

Here's a demo.

Related