Simple Function Template Program Example Get Maximum Number in C++
On this page (6sections)
Generic Programming
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types
Function Template Definition
A function template behaves same as normal function except that the template works with different data types.
Function Template Syntax
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
templete_identifier fn_name(templete_identifier .. args) {
return ...
}
Example Program
// Header Files
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
// Template Declaration
template<class T>
// Template Function
T getMaximun(T x, T y) {
if (x > y)
return x;
else
return y;
}
int main() {
int a, b, i;
float c, d, j;
cout << "Function Template Programs : Get Maximum Number \n";
cout << "Enter A,B values(integer):";
cin >> a>>b;
i = getMaximun<int>(a, b);
cout << "Result Max Int : " << i;
cout << "\n\nEnter C,D values(float):";
cin >> c>>d;
j = getMaximun<float>(c, d);
cout << "Result Max Float : " << j;
getch();
return 0;
}
Sample Output
Function Template Programs : Get Maximum Number
Enter A,B values(integer):56
89
Result Max Int : 89
Enter C,D values(float):17.99
9.01
Result Max Float : 17.99
Related Pages
Continue learning with these related tutorials and programs:
- OOP Programs — Browse all OOP Programs.
- Templates in C++ — Concept — function and class templates.
- Simple Class Template Program Example Get Maximum Number — More in templates in c.
- Simple Function Template Array Program Example : Search Number — More in templates in c.