Generic Programming Templates
Generic Programming Templates
1
Amity School of Engineering & Technology
Generic Programming
Amity School of Engineering & Technology
Function Templates
template <typename T>
void swap(T & lhs, T & rhs)
{ • The swap function template
T temp = lhs; takes a single type parameter, T
lhs = rhs; – interchanges values of two passed
rhs = temp; arguments of the parameterized type
}
int main () • Compiler instantiates the function
{
int i = 3; template twice in main
int j = 7; – with type int for the first call
long r = 12; – with type long for the second call
long s = 30; – Note that the compiler infers the
swap (i, j); type each time swap is called
// i is now 7, j is now 3 – Based on the types of the arguments
swap (r, s);
// r is now 30, s is now 12
return 0;
}
Amity School of Engineering & Technology
9
Amity School of Engineering & Technology
10
Amity School of Engineering & Technology
Class
// CPP code for bubble sort
Template on Editor- Bubble Sort
int main() {
// using template function int a[5] = {10, 50, 30, 40, 20};
#include <iostream> int n = sizeof(a) / sizeof(a[0]);
using namespace std;
// A template function to implement bubble sort. // calls template function
bubbleSort<int>(a, 5);
// We can use this for any data type that supports
// comparison operator < and swap works for it. cout << " Sorted array : ";
template <class T> for (int i = 0; i < n; i++)
void bubbleSort(T a[], int n) cout << a[i] << " ";
cout << endl;
{
for (int i = 0; i < n - 1; i++) return 0;
for (int j = n - 1; i < j; j--) }
if (a[j] < a[j - 1]) Output:
swap(a[j], a[j - 1]); Sorted array : 10 20 30 40 50
} 13
Amity School of Engineering & Technology
Class Templates Like function templates, class templates are useful when a class defines something that
is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array,
etc. Following is a simple example of template Array class.
template <typename T>
#include <iostream> Array<T>::Array(T arr[], int s) {
using namespace std; ptr = new T[s];
size = s;
template <typename T> for(int i = 0; i < size; i++)
Output:
class Array { ptr[i] = arr[i]; 1 2 3 4 5
}
private: template <typename T>
T *ptr; void Array<T>::print() {
for (int i = 0; i < size; i++)
int size; cout<<" "<<*(ptr + i);
cout<<endl;
public: }
Array(T arr[], int s); int main() {
int arr[5] = {1, 2, 3, 4, 5};
void print(); Array<int> a(arr, 5);
}; a.print(); 14
return 0; }
Amity School of Engineering & Technology
int main() {
A<char, char> a;
A<int, double> b;
return 0;
16
}