You can use variadic templates. One example for printing out all the passed argument is given below:
#include <iostream>
//provide an ordinary function to end recursion
void print ()
{
}
template<typename T, typename... Types>
void print (T firstArg, Types... args)
{
std::cout << firstArg << "\n"; // printing the very first argument passed
print(args...); // printing the rest of the argument by calling print()
}
int main()
{
print(1, 2, 3, "some string literal");//call function template print() with arguments `1`, `2`, `3` and `"some string literal"`
return 0;
}
In the above snippet, if we call print()
with one or more arguments then the templated version of print
will be used/called which just prints the very first argument passed(which is 1
in my example) using cout
and then calls print
with the remaining arguments(which are 2
, 3
and "some string literal
.
Now the whole process repeats. In particular, the very first argument 2
is printed using cout
and then print
is called with the remaining arguments(3
, "some string literal")
.
This goes on until there are no more arguments to pass and in this case when print
is called with no arguments then the ordinary non-template function print
will be used/chosen, thus ending the recursion.
The output of the above program can be seen here:
1
2
3
some string literal
Note that there are other ways as well like using fold expression(with C++17) to do the same. Also, in the above example, the arguments are passed by value. You can modify the program to pass them by reference according to your needs.
With C++17, you can use fold expression:
#include <iostream>
template<class... Args>
void print(const Args&... args)
{
(std::cout << ... << args) << "\n"; //uses fold expression
}
int main()
{
print(1, 2, 3, "some string literal");
return 0;
}