際際滷

際際滷Share a Scribd company logo
3/6/2016 C++Templates:ProgramtoSwapTwoNumbersUsingFunctionTemplate足TheCrazyProgrammer
http://www.thecrazyprogrammer.com/2013/11/c足templates足program足to足swap足two足numbers.html 1/4
By Admin | November 22, 2013 3 Comments
C++ Templates: Program to Swap Two Numbers
Using Function Template
What are Templates in C++?
Templates help in de ning generic classes and functions and
hence allow generic programming. Generic programming is an approach where
generic data types are used as parameters and the same piece of code work for
various data types.
Function templates are used to create family of functions
3/6/2016 C++Templates:ProgramtoSwapTwoNumbersUsingFunctionTemplate足TheCrazyProgrammer
http://www.thecrazyprogrammer.com/2013/11/c足templates足program足to足swap足two足numbers.html 2/4
with dierent argument types. The format of a function template is shown
below:
template<class T>
return_type function_name (arguments of type T)
{
 . . . .
.
 . . . .
.
}
I have written a program below which will swap two numbers
using function templates.
#include<iostream>
using namespace std;
template <class T>
void swap(T&a,T&b)   //Function Template
{
  T temp=a;
  a=b;
  b=temp;
}
int main()
{
  int x1=4,y1=7;
  oat x2=4.5,y2=7.5;
  cout<<Before Swap:;
  cout<<nx1=<<x1<<ty1=<<y1;
  cout<<nx2=<<x2<<ty2=<<y2;
  swap(x1,y1);
  swap(x2,y2);
  cout<<nnAfter Swap:;
  cout<<nx1=<<x1<<ty1=<<y1;
  cout<<nx2=<<x2<<ty2=<<y2;
  return 0;
3/6/2016 C++Templates:ProgramtoSwapTwoNumbersUsingFunctionTemplate足TheCrazyProgrammer
http://www.thecrazyprogrammer.com/2013/11/c足templates足program足to足swap足two足numbers.html 3/4
You May Also Like:
}
There are so many things that I have missed in this
tutorial. In below video templates are explained very nicely. I am sure that
after watching this video you will understand templates very easily.
Category: Functions
3 thoughts on C++ Templates: Program to Swap Two Numbers Using Function Template
C++ Basic Skills: Lesson 27 "Templates"
0:00 / 10:35
      
Rod Ochoa
November 22, 2013
995 1
3/6/2016 C++Templates:ProgramtoSwapTwoNumbersUsingFunctionTemplate足TheCrazyProgrammer
http://www.thecrazyprogrammer.com/2013/11/c足templates足program足to足swap足two足numbers.html 4/4
Try to do it without
T temp
Yes this can be done without temp as shown below.
a=a+b;
b=a-b;
a=a-b;
without using arithmetic operators as well as temporary variable
Neeraj Mishra
November 23, 2013
mantu pani
February 16, 2014

More Related Content

C++ Templates_ Program to Swap Two Numbers Using Function Template - The Crazy Programmer