Templates
C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.
Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type.
C++ provides two kinds of templates: function templates and class templates.
One can use function templates and class templates to write generic functions and generic class that can be used with arbitrary types.
For example, one can write searching and sorting routines which can be used with any arbitrary type.
For example, a class template for an array class would enable us to create arrays of various data types such as int array and float array.
Similarly we can define a template for a function, say mul(), that would help us to create various versions of mul() for multiplying int, float and double type values.
Example of class which creates an integer array
Class vector{
int *v;
int size;
Public:
vector(int m) { v= new int[size=m];
for (int i=0; i< size; i++) v[i]=0;
……}
Now if we want to create a float array again the class needed to be re-written. But if we use templates to create an array, the same template can be made use of to create different types of arrays
Syntax:
template <class T>
class classname
{
//
Different statements
};
Template
class vector
{
T *v; // type T vector
int size;
public:
vector(int m)
{ v=new T[size=m];
for(int i=0; i < size; i++)
v[i]=0; }
//other statements
};
- Class template definition is similar to an ordinary class definition except that prefix template and the use of type T.
- This prefix tells the compiler that we are going to declare a template and use T as a type name in the declaration.
- Thus the vector has become the parameterized class with the type T as its parameter.
- T may be substituted by any data type including the user defined types.
- Now, we can create vectors for holding different data types.
Example:
vector v1(10);
// 10 element int vector
vector v2(25);
// 25 element float vector
Syntax:
Classname objectname(arglist);
Pure Virtual Functions<< Previous
Next >> Class Templates to a stack
Our aim is to provide information to the knowledge
seekers.