Introduction
Templates allow us to specify a class parameter to a function or a class. We are used to passing parameters that are primitive types such int, float or class types such as string. With templates the type itself is a parameter and we can pass different types. This allows us a great deal of flexibility in writing our functions and classes.
Function templates
File: "template1.cpp"
// function template#include <iostream>using namespace std;template <class T> T GetMax (T a1, T b1){ T result; result = (a1>b1)? a1 : b1 ; return (result);}int main (){ int i1=5, j1=6, k1; long l1=10, m1=5, n1; k1 = GetMax<int>(i1, j1 ); n1 = GetMax<long>(l1, m1 ); cout << k1 << endl; cout << n1 << endl; return 0;}
Output:
$ g++ template1.cpp ; ./a.exe
6
10
template <class T> T GetMax (T a1, T b1)
The above is a declaration for the function. We are stating that we can pass "T" which is a type parameter to the function "GetMax" . It is used as:
k1 = GetMax<int>(i1, j1 );
n1 = GetMax<long>(l1, m1 );
We use the syntax "<int>" to specify the type that we are passing a type.
Class templates
File: "template2.cpp"
// class templates#include <iostream>using namespace std;template <class T>class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax ();};template <class T> T mypair<T>::getmax (){ T retval; retval = a>b? a : b; return retval;}int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0;}
The below shows how we can use a class template to store objects of different types.
File: "constainer.cpp"
// class templates#include <iostream>using namespace std;/*A conatiner to hold different kinds of objects.*/template <class T>class container { T* ptr ; int capacity = 10 ; int currentSize = 0 ; public: container () { ptr = new T[10] ; } void add( T obj1 ) { if ( currentSize >= 10 ) { cout << "Reached capacity." << endl ; return ; } ptr[ currentSize++ ] = obj1 ; } T get( int index ) { if ( index >= currentSize ) { cout << "Invalid index." << endl ; } else return ptr[ currentSize-1 ] ; }};int main (){ container<int> object1 ; container<string> object2 ; object1.add( 10 ) ; cout << object1.get(0) << endl ; object2.add( "James" ) ; cout << object2.get(0) << endl ; return 0;}