1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
using namespace std;
void print()
{
cout << "I am empty function and "
"I am called at last.\n";
}
template <typename T, typename... Types>
void print(T var1, Types... var2)
{
cout << var1 << endl;
print(var2...);
}
// Driver code
int main()
{
print(1, 2, 3.14,
"Pass me any number of arguments",
"I will print\n");
return 0;
}
|
https://www.geeksforgeeks.org/variadic-function-templates-c/
Does anyone know WHY the C++ committee chose to do variable functions like this?
The calls are:
print(1, 2, 3.14,"Pass me any number of arguments", "I will print\n");
print(2, 3.14,"Pass me any number of arguments", "I will print\n");
print(3.14,"Pass me any number of arguments", "I will print\n");
print("Pass me any number of arguments", "I will print\n");
The last one has 2 parameters and they coincide with the template, which is great:
|
template <typename T, typename... Types>
|
BUT THEN, on the last call, there is only one parameter for the 2 parameter template:
print("I will print\n");
So that either they must add an empty/NULL parameter at the end of the call during compile time...something like this (similar to '\0' of char array):
print(1, 2, 3.14,"Pass me any number of arguments", "I will print\n", NULL);
or there must be some logic to assign empty/NULL inside the function for "Types... var2" at the end? For which the latter takes some more processing and resources, and affects speed.
Why couldn't they make variable functions behind the scene as simple as this, where the variadic calls itself and just stops at the last one? What was wrong with coding C++ behind the scenes to work this way?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
using namespace std;
//NON-functioning program!!!!!!!!!!!!!
template <typename... Types>
void print(Types... varN)
{
cout << varN << endl;
}
// Driver code
int main()
{
print(1, 2, 3.14,
"Pass me any number of arguments",
"I will print\n");
return 0;
}
|