Benefits of generic programming
For example, normally we were doing this ↓
int Max(int n, int m)
{
return (n < m) ? n : m; // ternary operator
}
float Max(float n, float m)
{
return (n < m) ? n : m;
}
Observation:
Now we will use template ↓
template <class T>
T Max(T n, T m)
{
return (n > m) ? n : m;
}
Key feature:
At compile time:
int x = 3, y = 9;
r = Max(x, y);
Now compiler know that type is 'int'.
#include <iostream>
using namespace std;
template <class Type>
Type Max(Type a, Type b)
{
return (a > b) ? a : b;
}
int main()
{
float r;
r = Max(9, 4);
cout << "Maximum number is : " << r << endl;
r = Max(54.89, 98.78);
cout << "Maximum number is : " << r << endl;
return 0;
}
output ↓
Maximum number is : 9
Maximum number is : 98.78
#include <iostream>
using namespace std;
template <class Type>
void Print(Type a)
{
cout << "The value is : " << a << endl;
}
int main()
{
Print(9);
Print(9.5);
Print("Curry Power");
return 0;
}
Output ↓
The value is : 9
The value is : 9.5
The value is : Curry Power
#include <iostream>
using namespace std;
template <class Type>
Type add(Type num1, Type num2)
{
return num1 + num2;
}
int main()
{
int a = 10, b = 20;
float x = 10.2, y = 20.2;
cout << "Sum of " << a << " and " << b << " is = " << add(a, b) << endl;
cout << "Sum of " << x << " and " << y << " is = " << add(x, y) << endl;
return 0;
}
#include <iostream>
using namespace std;
template <class Type>
void swap(Type *num1, Type *num2)
{
Type temp = *num1;
*num1 = *num2;
*num2 = temp;
}
int main()
{
int a = 10, b = 20;
cout << " a and b before swap : " << a << " " << b << endl;
swap(&a, &b);
cout << " a and b after swap : " << a << " " << b << endl;
return 0;
}
#include <iostream>
using namespace std;
template <class Type>
Type max(Type arr[], int size)
{
Type max = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] > max)
max = arr[i];
}
return max;
}
int main()
{
int arr[] = {1, 2, 33, 4, 5};
int size = sizeof(arr) / sizeof(int);
cout << " max number in integer array is : " << max(arr, size) << endl;
float arr2[] = {1.1, 2.2, 33.3, 4.4, 5.5};
size = sizeof(arr2) / sizeof(int);
cout << " max number in float array is : " << max(arr2, size) << endl;
return 0;
}
Class Templates syntax ↓
Template <class Type>
Class class_name
{
// class body
};
Class Templates object Syntax ↓
Class_name <template argument> object_name;
Test<int> objINT;
Test<float> objFLOAT;
Program ↓
#include <iostream>
using namespace std;
template <class Type>
class Test
{
private:
Type n;
public:
void getValue()
{
cin >> n;
}
void printVal()
{
cout << "you entered : " << n << endl;
}
};
int main()
{
Test<int> objINT;
cout << "Enter integer value : ";
objINT.getValue();
objINT.printVal();
Test<float> objFLOAT;
cout << "Enter real value : ";
objFLOAT.getValue();
objFLOAT.printVal();
return 0;
}