Templates:

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

A template is a blueprint or formula for creating a generic class or a function.

The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>.

we can use templates to define functions as well as classes.

(1)Template Function:

#include<iostram.h>

#include<conio.h>

template<class x> void swap(x &a,x &b)

{
    x temp;
    temp=a;
    a=b;
    b=temp;
}
void main()
{
    int a=4,b=5;
    float p=3.5;q=4.2;
    cout<<"a="<<a<<" b="<<b<<"before calling swap function"<<endl;
    swap(a,b);
    cout<<"a="<<a<<" b="<<b<<"after calling swap function"<<endl;
    cout<<"p="<<p<<" q="<<q<<"before calling swap function"<<endl;
    swap(p,q);
    cout<<"p="<<p<<" q="<<q<<"after calling swap function"<<endl;
    getch();
}

(2)Template Class:

#include<iostram.h>

#include<conio.h>

template<class T>

class Sample

{

T a,b,c;

public:

void getdata()

{

cout<<"Enter the value of a & b

";

cin>>a>>b;

}

void sum()

{

c=a+b;

}

void putdata()

{

cout<<"

The sum="<<c;

}

};

int main()

{

clrscr();

Sample <int> S1;

S1.getdata();

S1.sum();

S1.putdata();

Sample <float> S2;

S2.getdata();

S2.sum();

S2.putdata();

getch();

return 0;

}