1

Hello I have this example about variadic function templates and patterns:

int& neg(int& x){ x = -x; return x;}

void f(int& x){
    std::cout << x << ", ";
}

template <typename T, typename...Args>
void f(T& x, Args&...args){
    f( neg(args)...);
}


int main(){

    int x = 1, y = 2, z = 3, a = 4;
    f(x, y, z, a);

    std::cout << x << ", " << y << ", " << z << ", " << a << '\n';

    cout << '\n';
}

The output:

-4, 1, -2, 3, -4
  • I don't know why I get this output and why shouldn't it be -1, -2, -3 -4?

  • Can someone explain to me what happens exactly when applying the pattern to the function argument pack: f(neg(args)...;? Thank you so much!

  • It looks to me that it starts the pattern in reverse order I mean from the end to the beginning. isn't it?

Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • 1
    Hint: `f(x,y,z,a)` calls `f(neg(y),neg(z),neg(a))`. In the next step, we call `f(neg(z),neg(a))` and then `f(neg(a))`. Count how many negations we have for each variable. Note that when we reach one argument (aka `a`) we print it from `f`, before printing all the variables again in `main`. – chi Oct 22 '21 at 23:44

0 Answers0