Variadic模板最大功能麻烦

Lal*_*and 3 c++ templates variadic-functions c++11

我正在尝试编写一个可变参数模板,用于查找任意数量的数字的最大值(这仅用于练习可变参数模板).

但是,我有点碰壁,无法理解为什么我当前的尝试根本不起作用,并在编译时因错误而失败:

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)'
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

#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);
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何修复我的可变参数模板?

Naw*_*waz 12

只需定义一个重载,它在可变参数函数模板上面有两个参数:

template <typename A> 
A myMax(A a,A b)      //this is an overload, not specialization
{
   if (a>b)
      return a;
   else
      return b;
}

template <typename A, typename ... Args>
A myMax(A a, A b, Args ... args)
{
   return myMax(myMax(a,b),args...);
}
Run Code Online (Sandbox Code Playgroud)

现在它将工作:http://www.ideone.com/R9m61

重载应该在实例化时可见,这在可变参数函数模板中.