Loading....
Coupon Accepted Successfully!

 

Function Templates With More Arguments

In the previous examples, we defined the constructors with arguments. In the same manner, we can also define member functions with generic arguments. The format is as follows:
 

Function Template Declaration

template<class T>

return_data_type function_name (parameters of template type)

{

Statement1;

Statement2;

Statement3;

}

 
17.7 Write a program to display the elements of integer and float array using template variables with member function.
#include<iostream.h>
#include<conio.h>
template <class T1, class T2>
class data
{
public:
void show (T1 a, T2 b)
{cout<<“\na=”<<a <<“ b=”<<b;}
};
int main()
{
clrscr();
int i[]={3,5,2,6,8,9,3};
float f[]={3.1,5.8,2.5,6.8,1.2,9.2,4.7};
data <int,float> h;
for (int m=0;m<7;m++)
h.show(i[m],f[m]);
return 0;
}
OUTPUT
a = 3 b = 3.1
a = 5 b = 5.8
a = 2 b = 2.5
a = 6 b = 6.8
a = 8 b = 1.2
a = 9 b = 9.2
a = 3 b = 4.7
 
Explanation: In the above program, array elements of the integer and float array are passed to the function show(). The function show() has two arguments of template type, that is, a and b. The show() function receives integer and float values and displays them. The output of the program is shown above.
 
17.8 Write a program to exchange values of two variables. Use template variables as function arguments.
#include<iostream.h>
#include<conio.h>
template <class E>
void exchange(E &a, E &b)
{
E t=a;
a=b;
b=t;
}
int main()
{
clrscr();
int x=5,y=8;
cout<<“\n Before exchange ”<<“x=”<<x <<“ y=”<<y;
exchange (x,y);
cout<<“\n After exchange ”<<“x=”<<x <<“ y=”<<y;
return 0;
}
OUTPUT
Before exchange x= 5 y= 8
After exchange x= 8 y= 5
 
Explanation: In the above program, exchange() is a user-defined function. It has two arguments of template type. In main(), the function exchange() is invoked, and two integers are passed. The function exchange() receives these values by reference. The values of two variables are exchanged with the help of temporary variable t. In the output, the values of variables x and y before and after execution of the function exchange() are displayed.
 
17.9 Write a program to define function template with multiple arguments.
#include<iostream.h>
#include<conio.h>
template <class A, class B, class C>
void show(A c,B i,C f)
{cout<<“\n c=”<<c <<“ i=”<<i <<“ f=”<<f;}
int main()
{
clrscr();
show(‘A’,8,50.25);
show(7,‘B’,70.89);
return 0;
}
OUTPUT
C = A i = 8 f = 50.25
C = 7 i = B f = 70.89
 
Explanation: In the above program, a template with A, B, and C classes are declared. The function show() has three arguments of type A, B, and C respectively. In main(), the function show() is invoked, and three values of different data types are passed. The function show() displays the values on the screen.




Test Your Skills Now!
Take a Quiz now
Reviewer Name