vendredi 31 août 2018

Is it possible to define a template parameter pack array

Possible duplicate: Is it possible to "store" a template parameter pack without expanding it?

Similar to the question above, I'd like to explore this more and store a variadic array.

template<size_t N, typename... Args>
void foo(Args(&...args)[N]) {
  Args[N]... args2; // compilation error
}

Is this possible to be accomplished?

The end goal is to be able to call foo, mutate a copy of its variadic array inputs, and execute some function on the mutations. So, something like:

template<typename F, size_t N, typename... Args>
void applyAsDoubled(F f, Args(&...args)[N]) {
  Args[N]... args2;
  doublerMutation(args2...); // doubles each argument; external function, assume it cannot avoid having a side-effect on its parameters

  for (int i = 0; i < N; i++)
    f(args2[i]...);
}

will be call and suffer no side-effects:

int A[N] = { 1, 2, 3, 4, 5 };
int B[N] = { 2, 2, 2, 2, 2 };

applyAsDoubled(printAdded, A, B);

will print 6, 8, 10, 12, 14 where A and B are not mutated. Just to clarify, the function doublerMutation is a dummy function to represent a function that will cause mutations for arguments and cannot be rewritten.

Aucun commentaire:

Enregistrer un commentaire