Thursday, June 25, 2009

Different functions for different data types will automatically be generated provided you define a template function



NOTE : -
THIS CONTENT IS NOT ORIGINAL

15. Different functions for different data types will automatically be generated provided you define a template function

Tired of defining the same function five times? One definition for
int type parameters, one definition for double type parameters, one definition for float type parameters... Didn't you forget one type? What if a new data type is used? No problem: the C++ compiler can automatically generate every version of the function that is necessary! Just tell it how the function looks like by declaring a template function:


using namespace std;
#include

template
ttype minimum (ttype a, ttype b)
{
ttype r;

r = a;
if (b < a) r = b;

return r;
}

int main ()
{
int i1, i2, i3;
i1 = 34;
i2 = 6;
i3 = minimum (i1, i2);
cout << "Most little: " << i3 << endl;

double d1, d2, d3;
d1 = 7.9;
d2 = 32.1;
d3 = minimum (d1, d2);
cout << "Most little: " << d3 << endl;

cout << "Most little: " << minimum (d3, 3.5) << endl;

return 0;
}


Output
Most little: 6
Most little: 7.9
Most little: 3.5



The function minimum is used three times in the above program, yet the C++ compiler generates only two versions of it: int minimum (int a, int b) anddouble minimum (double a, double b). That does the job for the whole program.

What would happen if you tried something like calculating
minimum (i1, d1)? The compiler would have reported that as an error. That's because the template states that both parameters are of the same type.

You can use an arbitrary number of different template data types in a template definition. And not all the parameter types must be templates, some of them can be of standard types or user defined (
char, int, double...). Here is an example where the minimum function takes parameters of any type (different or the same) and outputs a value that has the type of the first parameter:


using namespace std;
#include

template
type1 minimum (type1 a, type2 b)
{
type1 r, b_converted;
r = a;
b_converted = (type1) b;
if (b_converted < a) r = b_converted;
return r;
}

int main ()
{
int i;
double d;

i = 45;
d = 7.41;

cout << "Most little: " << minimum (i, d) << endl;
cout << "Most little: " << minimum (d, i) << endl;
cout << "Most little: " << minimum ('A', i) << endl;

return 0;
}


Output
Most little: 7
Most little: 7.41
Most little: -

(The ASCII code of character '-' is 45 while the code of 'A' is 65.)




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

No comments:

3G S

JAIL BREAK

iPHONE

BILL GATES

StEvE JoBs

steve jobs

STEVE JOBS

Steve Jobs

Love Country

SD

Burroughs

Lift

Joseph Johnson

Apple Rainbow

Apple Blue

Apple Laser Printer