Templates Notes
Templates Notes
Function Templates:
We can define a template for a function. For example, if we have an
add() function, we can create versions of the add function for adding the
int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can
be created for the array class that can accept the array of various types
such as int array, float array or double array.
Function Template
Generic functions use the concept of a function template. Generic
functions define a set of operations that can be applied to the various
types of data.
The type of the data that the function will operate on depends on the
type of the data passed as a parameter.
Example
#include <iostream>
using namespace std;
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
cout << myMax<int>(87, 76) << endl;
cout << myMax<double>(3.5, 5.5) << endl;
cout << myMax<char>('S', 'K') << endl;
return 0;
}
Output
87
5.5
S
#include <iostream>
using namespace std;
template<class T>
void Swap (T &first,T &second)
{
T temp;
temp = first;
first = second;
second = temp;
}
int main()
{
int ix,iy;
float fx,fy;
cout << "enter any two integers \n";
cin >> ix >> iy;
cout << "enter any two floating point numbers ? \n";
cin >> fx >> fy;
Swap (ix,iy);
cout << " after swapping integers \n";
cout << " ix = " << ix << " iy = " << iy << endl;
Swap (fx,fy);
cout <<" after swapping floating point numbers \n";
cout << " fx = " << fx << " fy = " << fy << endl;
return 0;
}
Output
int main()
{
sample <int> obj1;
sample <float> obj2;
cout << "Enter any two integers : "<< endl;
obj1.getdata();
obj1.sum();
cout << "Enter any two floating point numbers : " << endl;
obj2.getdata();
obj2.sum();
return 0;
}
Output
Enter any two integers :
45
67
sum of =112
Enter any two floating point numbers :
46.77
34.88
sum of =81.65