Function template:- It is also created for preparing family o generic functions as class template in which arguments of various data types are exist. Syntax of template function is same as general function’s syntax but before it template <class T> is used.
Syntax :- template < class T >
return_type function_name ( arguments );
statements;
..............
Body of function with type T
}
• Function template with multiple parameter –
Template function can also have two or more generic data type as template class which is differentiated by (,) comma operator.
Syntax:-
template < class T1, class T2 >
return_type function_name ( arg of type T1, type T2){
statements;
...............
...............
}
[NOTE:- A function which is created by function template is called template function. In this way a class which is created by class template is called template class].
Example:-
C++ program for swap function template.
#include<iostream>
#include<string>
template <class T>
void swap(T& x,T& y)
{
T temp;
temp=x;
x=y;
y=temp;
}
int main()
{
int a=44 ;
int b=66 ;
float s=4.4;
float t=6.6;
string mr="Ram";
string ms="Sita";
cout<<"Before swap a: "<<a<<" b: "<<b<<endl;
swap(a,b);
cout<<"After swap a: "<<a<<" b: "<<b<<endl;
cout<<"Before swap s: "<<s<<" t: "<<t<<endl;
swap( s, t );
cout<<"After swap s: "<<s<<" t: "<<t<<endl;
cout<<"Before swap mr: "<<mr<<" ms: "<<ms<<endl;
swap(mr,ms);
cout<<"After swap mr: "<<mr<<" ms: "<<ms<<endl;
return 0;
}
Syntax :- template < class T >
return_type function_name ( arguments );
statements;
..............
Body of function with type T
}
• Function template with multiple parameter –
Template function can also have two or more generic data type as template class which is differentiated by (,) comma operator.
Syntax:-
template < class T1, class T2 >
return_type function_name ( arg of type T1, type T2){
statements;
...............
...............
}
[NOTE:- A function which is created by function template is called template function. In this way a class which is created by class template is called template class].
Example:-
C++ program for swap function template.
#include<iostream>
#include<string>
template <class T>
void swap(T& x,T& y)
{
T temp;
temp=x;
x=y;
y=temp;
}
int main()
{
int a=44 ;
int b=66 ;
float s=4.4;
float t=6.6;
string mr="Ram";
string ms="Sita";
cout<<"Before swap a: "<<a<<" b: "<<b<<endl;
swap(a,b);
cout<<"After swap a: "<<a<<" b: "<<b<<endl;
cout<<"Before swap s: "<<s<<" t: "<<t<<endl;
swap( s, t );
cout<<"After swap s: "<<s<<" t: "<<t<<endl;
cout<<"Before swap mr: "<<mr<<" ms: "<<ms<<endl;
swap(mr,ms);
cout<<"After swap mr: "<<mr<<" ms: "<<ms<<endl;
return 0;
}
No comments:
Post a Comment