我想了解和了解可變參數模板的概念。 我碰到this例子就是Variadic模板示例不編譯
#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'重載。 –
這不是_running_,那是_compiling_。我真的很想知道可變模板如何導致運行時錯誤。 – MSalters