0

i started reading about templates and i got confused on the below.

template<class T>

T max(T t1, T t2)
{

    int


   if (t1 > t2)
      return t1;
return t2;
}

int main(){

 std::cout<<max<int>(120,14.55);
  return 0;
}

o/p is 120 .But when i compiled the above i got the below warning.

warning:passing double for argument 2 to T max(T, T) [with T = int]. why this warning came is my question since i have already instantiated for T max(int t1,double t2).

Because as per my understanding here if i explicitly mention only one data type(here int),other would be deducted from the argument type(14.55) by the compiler.That means T max(T t1, T t2) instantiates T max(int t1,double t2)in this case.I read this concept from some template documents in internet.

Please clear my doubts.else i cant proceed further

2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by subi09
1

The function header is this:

T max(T t1, T t2)

as for the actual parameters: (120,14.55); where 1 is an int, and the other is a double, thus the warning:passing double for argument 2 to T max(T, T) [with T = int].

You have the same type for the parameters as for the return value. So, if you privide arguments which are of different types you'll definitely get a warning (for numbers, since doubles/floats can be trunchated to ints, and ints converted to double/floats) and errors for other types.

If you declare your function like this:

#include <iostream>
using namespace std;
template <class T, class T1>
T1 maxs(T t1, T1 t2){
   if (t1 > t2)
      return (T1)t1;
   return t2;
}

int main(){
    cout<<maxs<int, double>(20, 4.6);
}

you will be able to have two types for that arguments, provided you declare them.
Template T is just a sort of macro for the compiler, which says that when the code will be run, every instance of the word T will be recplaced with the word given as the tempalte parameter when calling that function.

By your example, this would hold:

#include <iostream>
using namespace std;
template <class T>
T maxs(T t1, T t2){
   if (t1 > t2)
      return t1;
   return t2;
}

int main(){
    cout<<maxs<int>(20, 4)<<endl;
    cout<<maxs<double>(20.0, 20.1);
}

The same function, called once with int as the template parameter, and 2nd with double as the template parameter, acting in the same way.

Edited by Lucaci Andrew

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.