Templates in C++ || Write a code and return max value


 

A template is exmple of genereic programming , it is really powerful tool in C++. Idea is to pass data type as a parameter so code will not depent on data type.We need two  new keywords to support templates ‘template’ and ‘typename’. 

#include<iostream>
using namespace std;
template<typename T>T myMax(T a,T b)// template definition
{
return (a>b?a:b);//return a or b who is big
}
int main()
{
cout<<"Max int :"<<myMax<int>(2,3)<<endl;// taking int value
cout<<"Max in double :"<<myMax<double>(2.314,2.4)<<endl;//double value compare
cout<<"Max in alphabatical :"<<myMax('a','b');//char
return 0;
}
view raw .cc hosted with ❤ by GitHub
Max int :3     
Max in double :2.4
Max in alphabatical :b
Take three variable as input
#include<iostream>
using namespace std;
template<typename T>T myMay(T a,T b,T c)
{
return (a<b && b<c)?c:(a<b)?b:a;
}
int main()
{
cout<<"Max :"<<myMay<int>(5,7,9)<<endl;
cout<<"Max :"<<myMay<double>(1.2,1.3,1.4)<<endl;
return 0;
}
view raw .cc hosted with ❤ by GitHub
Max :9
Max :1.4

0 Comments