Write a C++ program to illustrate function template for swapping two numbers.
AIM:
Write a
C++ program to illustrate function template for swapping two numbers.
THEORY:
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:
1
2
3
4
|
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:
1
2
3
4
|
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:
1
2
3
4
5
|
template <typename T> // this
is the template parameter declaration
T max(T x, T y)
{
return (x
> y) ? x : y;
}
|
SOURCE CODE:
#include<iostream>
using
namespace std;
template<class
T>
void
swaping(T &a,T &b)
{
T t=a;
a=b;
b=t;
}
int main()
{
int x=5,y=8;
float a,b;
cout<<"\n Before
swapping"<<"x= "<<x<<"y= "<<y;
swaping(x,y);
cout<<"\n After swapping
"<<"x= "<<x<<"y= "<<y;
}
Labels: oop through c++ lab
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home