Search code examples
c++templatesc++17template-argument-deduction

template type deduction even with empty list


I was reading on cppreference that :

Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.

with followed examples :

std::tuple t1(1, 2, 3);              // OK: deduction
std::tuple<int,int,int> t2(1, 2, 3); // OK: all arguments are provided
std::tuple<int> t4(1, 2, 3);         // Error

So far, what I understood is :

  • when I give no template list, the temaplte argument will take places (like 1st example of tuple)
  • When I give empty or not all argument list, there will be error.

So in my example below :

template<typename T1, typename T2>
auto max(T1 a, T2 b) -> typename std::decay<decltype(true? a:b)>::type
{
   return  b < a ? a : b;
}

auto c = ::max('c', 7.2); //<<< Works as template deduction took place
auto d = ::max<int>('c', 7.2);  //<<<< WOrks !!! Why

So for the last line why did it work even I just provided one template list (T1) not both ? I was expecting error !!


Solution

  • Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place

    This is about deduction guides for classes, a new C++17 feature.

    Before C++17 was also an error

    std::tuple t1(1, 2, 3);
    

    because before C++17 was necessary explicit all template parameter for classes.

    So in my example below :

    Your example is about deduction for template functions.

    A completely different thing.

    For functions, you can explicit also some template parameters, non necessarily all of they.