Home Uncategorized Write a program to illustrate function template for swapping of two numbers.

Write a program to illustrate function template for swapping of two numbers.


AIM: Write a C++ program to illustrate function template for swapping two numbers.


Creating function templates in C++

At this point, you’re probably wondering how to actually create function templates in C++. It turns out, it’s not all that difficult.

Let’s take a look at the int version of max() again:

int max(int x, int y)
   Return(x > y)? x : y;

Note that there are 3 places where specific types are used: parameters x, y, and the return value all specify that they must be integers. To create a function template, we’re going to replace these specific types with placeholder types. In this case, because we have only one type that needs replacing (int), we only need one template type parameter.

You can name your placeholder types almost anything you want, so long as it’s not a reserved word. However, in C++, it’s customary to name your template types the letter T (short for “Type”).

Here’s our new function with a placeholder type:

T max(T x, T y)
   Return(x > y) ? x : y;

This is a good start — however, it won’t compile because the compiler doesn’t know what “T” is!

In order to make this work, we need to tell the compiler two things: First, that this is a template definition, and second, that T is a placeholder type. We can do both of those things in one line, using what is called a template parameter declaration:

template <typename T>// this is the template parameter declaration

T mac\x(T x, T y)
   Return ( x > y) ? x : y;


using namespace std;
template<class T>
void swaping(T &a,T &b)
   T t=a;

int main()
   int x=596,y=82031;
   float a,b;
   cout<<“Before swapping “<<“x = “<<x<<“\t y = “<<y<<endl;
   cout<<“After swapping “<<“x = “<<x<<“\t y = “<<y<<endl;

Before swapping x = 596 y = 82031
After swapping x = 82031 y = 596

Back to Programs.