on
Italy
- Get link
- X
- Other Apps
< >
which is followed by function declaration.template <class T> T some_function(T arg) { .... ... .... }
typename
instead of class in above example. When, an argument is passed to some_function( )
, compiler generates new version of some_function()
to work on argument of that type.
/* C++ program to display larger number among two numbers using function templates. */
/* If two characters are passed to function template, character with larger ASCII value is displayed. */
#include
using namespace std;
template
T Large(T n1, T n2)
{
return (n1>n2) ? n1:n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout<<"Enter two integers: ";
cin>>i1>>i2;
cout<>f1>>f2;
cout<>c1>>c2;
cout<
OutputT
in above example. During run-time,
when integer data is passed to template function then, compiler knows
the type to use is int. Similarly, when floating-point data and char
data is passed, it knows the type to use is float and char respectively.
After knowing the information of a type, it generates the specific
version of Large( )
to work for that type.
/* C++ program to swap datas entered by user. */
#include
using namespace std;
template
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1=1, i2=2;
float f1=1.1, f2=2.2;
char c1='a', c2='b';
cout<<"Before passing data to function template.\n";
cout<<"i1 = "<Output
Before passing data to function template. i1 = 1 i2 = 2 f1 = 1.1 f2 = 2.2 c1 = a c2 = b After passing data to function template. i1 = 2 i2 = 1 f1 = 2.2 f2 = 1.1 c1 = b c2 = a
Comments
Post a Comment