Wednesday, October 31, 2012

What is Template

Template helps us to create the generic functions and classes. In the generic function or class, the type of data upon which the function or class operates and specified as a parameters.

//Function Template
#include <iostream>
using namespace std;

template <class T>
T GetMax (T a, T b)
{
    T result;
    result = (a>b)?a:b ;
    return (result);
}


int main()
{
    int i = 5, j = 6, k;
    long l = 10, m = 5, n;

    k = GetMax<int>(i,j);
    n = GetMax<long>(l,m);

   
    cout << k << endl;
    cout << n << endl;
}

OUTOUT:
6
10 

int x, y;
GetMax <int> (x,y);
when the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appereance of mytype by the type passed as the actual template parameter (int in this case) and then calls it. this process is automatically performed by the compiler and is invisible to the programmer.
______________________________________________________________________

// function Template 2
#include <iostream>
using namespace std;

template <class T>
T GetMax(T a, T b)
{
    T result;
    result = (a>b)?a:b ;
    return (result);
}

int main()
{
    int i = 5, j = 6, k;
    long l = 10, m = 5, n;
    k = GetMax(i,j);
    n = GetMax(l,m);
         //Notice here we don't declare the type
   
    cout << k << endl;
    cout << n << endl;
}

OUTOUT:
6
10

Notice how in this case, we called our function template Getmax() without explicitly specifying the type between angle-brackets <>. The compiler automatically determine what type is needed on each call.  

No comments:

Post a Comment