Templates in Cpp / C++ swapping of 2 numbers


This program is for Swapping of Numbers using Templates . This is a part of Mumbai University MCA Colleges C++ Programs MCA. 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.


#include<iostream.h>
#include<conio.h>

template<class T>T swap(T &first,T &second)
{
T temp;
temp=first;
first=second;
second=temp;
return(0);
}

int swap(int &a,int &b);
float swap(float &x,float &y);
void main()
{
int ix,iy;
float fx,fy;
clrscr();
cout<<"\nEnter two Integers : ";
cin>>ix>>iy;
cout<<"\nEnter two Floating point Numbers : ";
cin>>fx>>fy;
cout<<"\nBefore Swap :";
cout<<"\n  a : "<<ix;
cout<<"\n  b : "<<iy;
swap(ix,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;
swap(fx,fy);
cout<<"\n\nAfter Swap :";
cout<<"\n  x : "<<fx;
cout<<"\n  y : "<<fy;
getch();
}

Hope this Program is useful to you in some sense or other. Keep on following this blog for more Mumbai University MCA College Programs. Happy Programming and Studying.

No comments:

Post a Comment