We will take a very simple function to swap two integer type numbers to explain the syntax for function templates in C++.
Code:
void Swp(int& n1, int& n2)
{
int n3 = n1;
n1 = n2;
n2 = n3;
}
But now consider if we had to swap the float type, char type and string type data. Although similar type of action is performed but with different data-types. It would really be time consuming to code such querry that too which is performing same action. Thus can the need for function templates.
Now the above code using function template would be:
Code:
template<typename N>
void Swp(N& n1, N& n2)
{
N n3 = n1;
n1 = n2;
n2 = n3;
}
void main()
{
int a,b;
float p,q;
char w,x;
...
Swp(a,b);
Swp(p,q);
Swp(w,x);
.
.
.
}
Bookmarks