Graeme
Graeme

Reputation: 4592

Calling variadic template function with no args failing

Given the following code:

#include <iostream>

template <typename... Args>
void foo(Args&&... bargs, Args&&... aargs)
{
    std::cout << "Hello" << std::endl;
}

int main()
{
    foo<int, double>(1, 2.0, 3, 4.0); //OK
    foo<char>('c', 'd'); // OK
    foo(); //FAIL
}

I get the following compiler error:

In function 'int main()':
15:9: error: no matching function for call to 'foo()'
15:9: note: candidate is:
6:6: note: template<class ... Args> void foo(Args&& ..., Args&& ...)
6:6: note:   template argument deduction/substitution failed:
15:9: note:   candidate expects 1 argument, 0 provided

Is it possible to call such a function with no args? Can the function be changed to support zero or more args?

Upvotes: 3

Views: 843

Answers (1)

CliffordVienna
CliffordVienna

Reputation: 8235

You have to specify a version of the function without args:

#include <iostream>

template <typename... Args>
void foo(Args&&... bargs, Args&&... aargs)
{
    std::cout << "Hello with args" << std::endl;
}

void foo()
{
    std::cout << "Hello without args" << std::endl;
}

int main()
{
    foo<int, double>(1, 2.0, 3, 4.0); //OK
    foo<char>('c', 'd'); // OK
    foo(); // Also OK now
}

Upvotes: 5

Related Questions