Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template as first arguments

I want to write a generic template function that accepts and calls a number of different functions and performs additional setup and teardown operations. The functions signatures differ in the first arguments, such as:

void foo(int i, void* self, (*callback)(void*, int i));
void bar(bool s, bool r, void* self, (*callback)(void*, int i));

I also want to pick out the self argument and the callback, but letting the arguments in front of them vary. I understand this must be hard to do with variadric templates due to how the unpacking works; is there any way around it?

like image 600
Rolle Avatar asked Oct 21 '25 18:10

Rolle


1 Answers

If I understand your question correctly, your issue is to use variadic templates in any order as an argument, except as the first one. Well, thankfully all these are valid:

template<class T, class ...Args> void call1(int y, T first, Args ... args, int x);
template<class T, class ...Args> void call2(int y, int x, T first, Args ... args);
template<class T, class ...Args> void call3(Args ... args, T first, int y, int x);
Edit:
Automatic template deduction will only work for call2
Thanks to @Human-Compiler

Of course, variadic templates are dealt with using recursion, so, in order to handle them correctly, you'll also need a function to call should there be no first argument provided:

void call1(int y, int x);

An example, which will just blindly call the first x functions:

void print()
{
  std::cout << "print";
}
void call(int x)
{
  return;
}
template<class T, class ...Args> void call(int x, T f, Args ... args)
{
  if(x <= 0) return;
  f();
  call(--x, args...);
}

int main()
{
  call(3, print, print, print);
}
like image 94
Mikdore Avatar answered Oct 24 '25 07:10

Mikdore



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!