class templates
1 minute read
What are class templates? What is need for class templates? Give example?
v Class template is a template which allows to create a family of class with different data structure.
v For example: suppose we make a class vector that can store an array of integer numbers and perform the scalar product of two integer vectors.
v Now suppose we want to define a vector that can store an array of float values. We can simply do this by replacing the appropriate integer declarations with float in vector class. This means redefining the vector class.
v But if make the vector-class with data type as a parameter and then use this class to create a vector of any data type.
v This means that we are creating generic class by using the class template.
v Example:
#include <iostream.h>
const size =3;
template <class T>
class vector
{
T* v; // type T vector
public:
vector()
{
v = new T[size];
for (int i = 0; i < size; i++)
v [i] = 0;
}
vector (T* a)
{ for(int i = 0; i < size; i++)
v[i] = a[i];
}
T operator* (vector &y)
{ T sum =0;
for(int i = 0; i < size; i++)
sum += this -> v[I] * y.v[i];
return sum;
}
};
int main()
{ int x[3] = {1, 2, 3};
int y[3] = {4, 5, 6};
vector <int> v1;
vector <int> v2;
v1 = x;
v2 = y;
int R = v1 * v2;
cout << “R = “ << R << “\n”;
return 0;
}
v The output of the program would be:
R = 32