Search code examples
c++templatesc++11variadic-functions

Variadic template max function trouble


I am trying to write a variadic template for finding the maximum of an arbitrary amount of numbers (this is just for practicing variadic templates).

However, I have sort of hit a wall and can't understand why my current attempt simply does not work, and fails at compile time with the error:

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)'

My code is as follows:

#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);
}

Can anyone tell me how to fix my variadic template?


Solution

  • Just define the overload which takes two arguments above the variadic function template:

    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...);
    }
    

    Now it will work: http://www.ideone.com/R9m61

    The overload should be visible at the point of instantiation, which is in the variadic function template.