【发布时间】:2016-04-08 23:46:35
【问题描述】:
我正在尝试掌握和理解可变参数模板的概念。 我遇到了this 例子
#include <iostream>
using namespace std;
//Output function to output any type without type specifiers like printf() family
template <typename T, typename ...P>
void output(T t, P ...p)
{
cout << t << ' ';
if (sizeof...(p)) { output(p...); }
else { cout << '\n'; }
}
//Since variadic templates are recursive, must have a base case
void output() { cout << "\n"; }
//Test it
int main()
{
//output();
output('5', 2);
return(0);
}
但是当我尝试运行它时,我得到了错误
main.cpp: In instantiation of 'void output(T, P ...) [with T = int; P = {}]':
main.cpp:10:29: required from 'void output(T, P ...) [with T = char; P = {int}]'
main.cpp:21:16: required from here
main.cpp:10:29: error: no matching function for call to 'output()'
if (sizeof...(p)) { output(p...); }
^
main.cpp:7:6: note: candidate: template<class T, class ... P> void output(T, P ...)
void output(T t, P ...p)
^
main.cpp:7:6: note: template argument deduction/substitution failed:
main.cpp:10:29: note: candidate expects at least 1 argument, 0 provided
if (sizeof...(p)) { output(p...); }
^
关于如何修复它的任何建议。谢谢
【问题讨论】:
-
交换两个
output重载。 -
那不是运行,那是编译。我真的很想知道可变参数模板如何导致运行时错误。