Webocreation

Tuesday, September 22, 2009

TEMPLATES in C++

TEMPLATES

Templates are one of the features added in C++ recently. It is a new concept which enable is to define generic classes and functions and thus provides supports for generic programming and provides flexible
Generic programming is an approach where generic types are used as parameters in algorithms so that they work for variety of suitable data-types and data structure.
A template can be used to create a family of classes or functions. For e.g.: a class template for an array class would enable us to create array of various data-types such ass int array and float array etc.
A template can be considered as a kind of macro when ana object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by specific data type at the time of actual use of class or function, the templates are sometime also called vparameterized classes or function.
Class templates

The general format of a class template is:
Template<class T>
Class classname
{
…………
//class member specification
//with anonymous type T
//when even appropriate
……….
};

The syntax for defining an object of a template class is:
classname<type>objectname(arg_list);

#include<>m.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(in i=0;i<size;i++)
Sum+=this->v[i]*y.v[i];
return sum;
}
};
Void 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<<endl;
float x1[3]={1.1, 2.2,3.3};
float x2[3]={4.4,5.5,6.6};
vector<float> v3;
vector<float>v4;
v3=x1;
v4=x2;
float R1=v3*v4;
cout<<”R1=”<<R1;
}

Class template with multiple parameters:

Template <class T1, class T2>
Class classname
{
-------------------
--------------------// body of class
}

No comments:

Post a Comment