Thursday, 7 February 2013

function template in c++

//find absolute value of a number
#include<iostream.h>
#include<conio.h>

template <class T>       //function templete
T abs(T n)
{
return (n<0) ? -n : n;
}

int main()
{
int int1=5;
int int2=-6;
long lon1=70000L;
long lon2= -80000L;
double dub1= 9.95;
double dub2= -10.15;

cout<<"\nabs("<<int1<<")="<<abs(int1);
cout<<"\nabs("<<int2<<")="<<abs(int2);
cout<<"\nabs("<<lon1<<")="<<abs(lon1);
cout<<"\nabs("<<lon2<<")="<<abs(lon2);
cout<<"\nabs("<<dub1<<")="<<abs(dub1);
cout<<"\nabs("<<dub2<<")="<<abs(dub2);
cout<<endl;
getch();
return 0;
}
/*Templates make it possible to use one function or class to handle many different data types.

Ordinarily one function at a time can return only one data type; means for each data type,
separate function is to be defined. Thus rewriting the same function body over and over for
different types is time consuming and wastes space in the listing. But by using function templates,
we write a function just once, and have it work for many different data types.*/

0 comments:

Post a Comment