Search code examples
c++templatestemplate-argument-deduction

How the first argument in template parameters list getting skipped form call parameters?


I was experimenting to find how arguments are deduced when we use templates in c++, I came though a case which was strange for me.

As per my understanding template parameters should be present in call parameters. But in the code below, I tried to skip the first template parameter and the code compiles and runs fine. I think I have gaps in my understanding.

This is just an experimental code:

#include <iostream>
#include <cstring>
#include <string>
#include <typeinfo>
using namespace std;

template <typename T, typename T1>
T1 const& max (T1 const & a, T1 const & b) //"typename T" is not present here
{
    cout<<"inside func max a: "<<typeid(a).name()<<endl;
    cout<<"inside func max b: "<<typeid(b).name()<<endl;
return a < b ? b : a;
}

int main ()
{
  ::max<double>(7, 42);
  cout<<typeid(::max<double>(7, 42)).name();
}

This code runs fine, no errors. But how it managed to skip typename T parameter. Can somebody please explain or provide some link on this.


Solution

  • how it managed to skip typename T parameter

    T is explicitly specified as double. And T1 could be deduced from the arguments.

    In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments.

    Given

    ::max<double>(7, 42); // T is specified as double, T1 is deduced as int from 7 and 42
    

    You can specify T1 too, such as

    ::max<double, long>(7, 42); // T is specified as double, T1 is specified as long
                                // then 7 and 42 will be converted to long when being passed
    

    Note that only T1 could be deduced (from arguments); you have to always specify T explicitly.