-1

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.

  • 1
    The recursive calls will be `print(1,2,3)` then `print(2,3)` then `print(3)` then `print()` and that last call there is no matching function that takes no arguments – Cory Kramer Jul 08 '22 at 12:17

2 Answers2

9

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"), ...);
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You need to define two separate overloads, with an empty one for the terminating case:

void print(){
    cout << endl;
}
template <typename T, typename... Types>
void print(T value, Types... args){
    cout << value << " ";
    print(args...);
}
codemurt
  • 21
  • 4
  • 4
    While this code may solve the problem the answer would be a lot better with an explanation on how/why it does. Remember that your answer is not just for the user that asked the question but also for all the other people that find it. – NathanOliver Jul 08 '22 at 12:18
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 09 '22 at 00:01