Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ metaprogramming to split the function arguments and pass them one by one to another function

Tags:

c++

c++17

So I have a variable argument function with different argument types; I would like to pass every argument to another function which is a C function. As an example; for a case with two arguments;

void function(int *a, double *b) needs to call
{
  bindToFunc(0, a);
  bindToFunc(1, b);
}

void function(int *a, double *b, float *c) needs to call
{
  bindToFunc(0, a);
  bindToFunc(1, b);
  bindToFunc(2, c);
}

template<typename... T>
void function(T ...)
{
  // has to have
  // 
  // bindToFunc(0, T0) ....
  // bindToFunc(n-1, Tn-1);
}

I tried using,

template <int I, class... Ts> 
decltype(auto) get(Ts &&... ts) 
{
  return std::get<I>(std::forward_as_tuple(ts...));
}

but since I is the template parameter, it is a compile time variable and hence we can not use it in with a for loop.

like image 698
JimBamFeng Avatar asked Dec 07 '25 07:12

JimBamFeng


1 Answers

With C++17 and fold expression, you might do:

template<typename... Ts>
void function(Ts... args)
{
    [[maybe_unused]] int i = 0; // Not used for empty pack.
    (bindToFunc(i++, args), ...);
}
like image 188
Jarod42 Avatar answered Dec 08 '25 21:12

Jarod42