0

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Vikram Singh
  • 273
  • 1
  • 3
  • 10

1 Answers1

3

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • thxx songyuanyao, for your answer, can you give me some links, or suggest some good books, where I can clear all my doubts on this. – Vikram Singh Jun 26 '18 at 01:23
  • 1
    @VikramSingh As I linked in my answer, [cppreference.com](https://en.cppreference.com/w/) is a good site for it. And about books you can see [here](https://stackoverflow.com/q/388242/3309790). – songyuanyao Jun 26 '18 at 01:25
  • 1
    @VikramSingh, [good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), and you can refer to the standard's [template deduction](https://timsong-cpp.github.io/cppwp/temp.deduct) section. – Joseph D. Jun 26 '18 at 01:27