Class template in C++

Class template :- A class template stores any general class and its related data members and associated functions. Syntax of class template is as follows –
Syntax :- 
template <class T>
 class class_name {
 Data_member specifications;
............
 Functions declaration/definition;
 ...........
};

• Class template definition :- It is similar to class function but before it template<classT> is used. It is prefix which tells to compiler that class template of T type is prepared. Thus vector class is parametrized class whose object is T.
Object of template class is defined as follows –
Vector<int> v1 (3, &x);
Vector<int> v2 (3, &y);
   
Process of preparing class object from class template is called instantiation. After that compiler analysis error.

Example:-
C++ program for class template of vectors.
#include<iostream.h>
#include<conio.h>
template <class T>
class vector{
T *v;
int size;
public:
vector(int m){
size=m;
v=newT[size];
for(int i=0;i<size;i++){
v[i]=0;
}
vector(int m, T*a){
size=m;
v=newT[size];
for(i=0;i<size;i++){
v[i]=a[i];
}
T operator*(vector &y){
Tmul=0;
for(int i=0;i<size;i++){
mul=this->[i]*y->v[i];
return mul;
}};
void main(){
int x[3]={1,2,3};
int y[3]={2,-1,2};
vector<int>v1;
vector<int>v2;
v1=x;
v2=y;
int r=v1*v2;
cout<<"Multiplication= "<<r <<endl;
getch();
}

• Class template with multiple parameter :- In a class template two or more type of generic data type are exist which are differentiated by (,) comma operator.
Syntax :- template < class T1, class T2 >
                 class class_name{
                data_member specifications;
. . . . . . . . . . . .
               member function definition;
               ..........
                };

Example:-
C++ program for class template of vectors with multiple parameters.
#include<iostream.h>
#include<conio.h>
template <class T1,class T2>
class test{
T1 a;
T2 b;
public:
test(T1 x,T2 y){
a=x;
b=y;
}
void show(){
cout<<"a= "<<a<<endl<<"b= "<<b<<endl;
}};
void main(){
test<float,int> test1(1.23,123);
test<int,char> test2(123,'C');
test1.show();
test2.show();
getch();
}

No comments:

Post a Comment