# Thread: How to create a variadic function that are recursive with the given pseudo code in C+

1. ## How to create a variadic function that are recursive with the given pseudo code in C+

I am trying to make a recursive variadic template function that works in the following example. The example shows no practicality and is only used to help better understand what I'm asking. So, basically I have a function that takes an infinite amount of parameters of the same type and it recursively calls itself with all but the last parameters. Then, once it finally reaches two parameters the next unction serves as the termination of the function. I know the answer isn't trivial and I'm having trouble figuring out exactly what to do. Any help or direction would be appreciated! Thanks.

Code:
```template <typename... Ts>
void test(int& a, int& b, Ts&... ts){
test(a, b, ... ); //all but the last parameter

//last parameter argument is processed here

}

void test(int& a, int& b){
//end of recursion
}

int main(int argc, char** argv){

int a = 3;
int b = 5;
int c = 6;
int d = 4;

test(a, b, c, d);

return 0;
}```

2. I am not very familiar with variadic function templates, and I'm afraid that I have never seen an example in which the parameter pack is not at the end. This means that you can only process the first (or first N) variadic arguments, and then unpack the rest, whereas you want to unpack all the variadic arguments other than the last argument. I gave it a try:
Code:
```#include <iostream>

void test(int& a, int& b)
{
std::cout << "end: " << a << ", " << b << std::endl;
}

template <typename T>
void test(int& a, int& b, T& c)
{
test(a, b);
std::cout << c << std::endl;
}

template <typename T, typename... Ts>
void test(int& a, int& b, Ts&... ts, T& c)
{
test(a, b, ts...);
std::cout << c << std::endl;
}

int main()
{
int a = 3;
int b = 5;
int c = 6;
int d = 4;

test(a, b, c, d);

return 0;
}```
but it failed. You may want to change your requirements so you can write this instead:
Code:
```#include <iostream>

void test(int& a, int& b)
{
std::cout << "end: " << a << ", " << b << std::endl;
}

template <typename T>
void test(int& a, int& b, T& c)
{
test(a, b);
std::cout << c << std::endl;
}

template <typename T, typename... Ts>
void test(int& a, int& b, T& c, Ts&... ts)
{
test(a, b, ts...);
std::cout << c << std::endl;
}

int main()
{
int a = 3;
int b = 5;
int c = 6;
int d = 4;

test(a, b, d, c);

return 0;
}```
(Notice that c and d are swapped in the call in main.)

Popular pages Recent additions