给出以下代码:
#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
}
我收到以下编译错误:
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
是否可以在没有args的情况下调用这样的函数?可以更改功能以支持零个或多个args吗?
答案 0 :(得分:3)
您必须指定不带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
}