Templates in Cpp / C++ swapping of 2 numbers

Ram Pothuraju
This program is for Swapping of Numbers using Templates . It uses the concept of template to swap 2 numbers.

Templates in C++ or CPP are basically used when we are not sure of the datatype which the user is going to input. We wrap the data in those templates and perform operations on them. Templates can be said as generic data types in C++ or CPP. This is a simple example to show how different numbers of different data types are swapped using a single function.


template<class T>T swap(T &first,T &second)
 T temp;

int swap(int &a,int &b);
float swap(float &x,float &y);
void main()
 int ix,iy;
 float fx,fy;
 cout<<"\nEnter two Integers : ";
 cout<<"\nEnter two Floating point Numbers : ";
 cout<<"\nBefore Swap :";
 cout<<"\n  a : "<<ix;
 cout<<"\n  b : "<<iy;
 cout<<"\n\nAfter Swap :";
 cout<<"\n  a : "<<ix;
 cout<<"\n  b : "<<iy;

 cout<<"\n\nBefore Swap :";
 cout<<"\n  a : "<<fx;
 cout<<"\n  b : "<<fy;
 cout<<"\n\nAfter Swap :";
 cout<<"\n  x : "<<fx;
 cout<<"\n  y : "<<fy;

Post a Comment


Post a Comment (0)