Using templates programmers can create abstract class that define the behavior of the classes without actually knowing what data types will be handled by the class operation. Such class are known as class templat. Syntax for creating a class template is as follow:
1 2 3 4 5 6 7 8 |
template < class Type1, class Type2, ... > class ClassName { ... //Body of the class ... }; |
Syntax for creating an objects of the template class is as follow:
1 2 3 |
ClassName<Type> ObjectName(params–list); |
The process of creating an objects of a template class or creating a specific classes from a class template is called instantiations. The instantiated object of a template classes is known as specializations. If a class template is specialized by some but not all parameter it is called partial specialization and if all the parameter are specialized, it is a full specializations.
Following program demonstrate creating a class template and using it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include <iostream> using namespace std; template < class Type > class Swappers { public: Type xa, yb; public: Swappers(Type xa, Type yb) { this -> xa = xa; this -> yb = yb; } void swap() { Type temps; temps = xa; xa = yb; yb = temps; } void display() { cout << "xa=" << xa << "", yb = "<<yb<<endl; } }; int main() { Swappers < int > iobj(10, 20); cout << "Before swaps:" << endl; iobj.display(); iobj.swaps(); cout << "After swap:" << endl; iobj.display(); Swappers < float > fobj(10.3, 20.6); cout << "Before swaps:" << endl; fobj.display(); fobj.swap(); cout << "After swaps:" << endl; fobj.display(); return 0; } |
Output for the above programs is as follows:
1 2 3 4 5 6 7 8 9 10 |
Before swaps: x = 10, y = 20 After swaps: x = 20, y = 10 Before swaps: x = 10.3, y = 20.6 After swaps: x = 20.6, y = 10.3 |
The template data type allows default argument. Syntax for specifying default data type is as follow:
1 2 3 4 5 6 7 8 9 |
template<class Type1, class Type2 = int> class ClassName { ... //Body of the class ... }; |
We can define member functions of a class templates outside the classes. Syntax for doing it is as follow:
1 2 3 4 5 6 7 8 9 |
template<class Type> return–type ClassName<Type> :: function–name(params–list) { ... //Body of function ... } |
Take your time to comment on this article.