我想寫一個可變模板來找到最大的任意數量的數字(這只是爲了練習可變模板)。Variadic模板最大功能麻煩
不過,我已經有點碰了壁,不能明白爲什麼我當前的嘗試根本不起作用,而且在編譯時有錯誤失敗:
prog.cpp: In function 'A myMax(A, A, Args ...) [with A = int, Args = {}]':
prog.cpp:7:35: instantiated from 'A myMax(A, A, Args ...) [with A = int, Args = {int}]'
prog.cpp:22:26: instantiated from here
prog.cpp:7:35: error: no matching function for call to 'myMax(int)'
我的代碼如下:
#include <iostream>
template <typename A, typename ... Args>
A myMax(A a, A b, Args ... args)
{
return myMax(myMax(a,b),args...);
}
template <typename A>
A myMax(A a,A b)
{
if (a>b)
return a;
else
return b;
}
int main()
{
std::cout<<myMax(1,5,2);
}
誰能告訴我如何修復我的variadic模板?
OK,但是一旦你完成學習,請進入返回並使用'std :: max' :-) – 2012-01-14 04:52:32