Thursday, 21 September 2017

Function template to swap two numbers in C++

/*
 Demonstrating function template
*/

#include "iostream"
using namespace std;

template <class T>
void swaparg(T &a, T &b){
 T temp;
 temp = a;
 a = b;
 b = temp;
}

int main(){
 int x=10, y=20;
 double dx=25.5, dy=30.1;

 cout<<"\n Before swapping x & y "<<x<<" "<<y;
 cout<<"\n Before swapping dx & yy "<<dx<<" "<<dy;
 
 swaparg(x,y);
 swaparg(dx,dy);
 cout<<"\nAfter swapping X & Y "<<x<<" "<<y;
 cout<<"\n After swapping dx & yy "<<dx<<" "<<dy<<endl;
 
 return 0;
}

/*
 OUTPUT

[pavan@localhost Template]$ g++ TempDemo1.cpp
[pavan@localhost Template]$ ./a.out 

 Before swapping x & y 10 20
 Before swapping dx & yy 25.5 30.1
After swapping X & Y 20 10
 After swapping dx & yy 30.1 25.5
[pavan@localhost Template]$ 
*/

No comments: