Search code examples
c++variadic-templatesstdtuple

Storing arguments and function and using them in another function


Welcome, this is very rare use-case question.
So, here is what I'm trying to do - lets say I have a variadic template function which takes T ...args and a function type FuncT funcName, so here is what we have so far:

template<typename FuncT, typename ...T>
void myFunction(FuncT (*funcName), T ...args);

Now, I want to store my function at void (*)() (this store functions). This works just fine.

std::deque<void (*)()> functions;
func = functions.front();
func(std::forward<T>(args)...); //args is vardict template argument

Now, I can just pass a function to my function as in:

template<typename FuncT, typename T>

int sharedArgument;

void setArg(int x){
  sharedArgument = x;
}
template<typename FuncT>
void myFunction(FuncT funcName){
  funcName(sharedArgument);
}

void function(int i){
  std::cout << i;
}

int main(){
  setArg(5);
  myFunction(function);
}

Now, I know this is unnecesary, but i want to present a more complicated problem that im having trouble with.

When i want to store arguemnts, I will probably use std::tuple, its design to store arguments, but
Main question is:
How do i store variable amount of arguments in tuple and then perfectly forward them as normal arguments to some function, so that function receiving

function(std::tupleArgumentsHere...);

will read it as

function(5, 42, "yes", 3.14);

I will use this to store arguments and pass them to std::thread.


Thank you, Cheers.


Solution

  • Use std::apply. It is new in . If you cannot, write your own.

    In , make an index sequence the same length as your tuple. Then func(std::get<Is>(std::forward<Tup>(tup))...).

    In do the same thing but write your own index sequence.