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’.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Max int :3 Max in double :2.4 Max in alphabatical :bTake three variable as input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Max :9 Max :1.4
0 Comments
If you have any doubt and suggestion Please let me know