I'm currently working on a variadic function using template, however, I keep getting the same error:
C2780: 'void print(T,Types...)': expects 2 arguments - 0 provided
even if it is the simplest one:
template <typename T, typename... Types>
void print(T var1, Types... var2)
{
cout << var1 << endl;
print(var2...);
}
int main() {
print(1, 2, 3);
}
the same error again. I wonder what's wrong.
CodePudding user response:
Your calls to print
will be like this:
print(1, 2, 3);
print(2, 3);
print(3);
print();
Your template function needs at least one argument (var1
), and there is no function that takes zero arguments.
This can easily be solved by adding another function overload to handle the "no argument" case:
void print()
{
// Do nothing
}
Now this will be called in the
print();
case, and will end the recursion.
If C 17 is possible, then fold expressions are available and you could do it with only a single function:
template <typename... Types>
void print(Types&&... var)
{
((std::cout << var << "\n"), ...);
}
CodePudding user response:
Try this:
void print(){}
template <typename T, typename... Types>
void print(T value, Types... args){
cout << value << endl;
print(args...);
}