Friday, April 17, 2009

Function Templates

Function Templates
Like class templates, we can also define function templates that could be used to create a family of functions with different argument types. The general format of a function template is:
Syntax:

Template <>
returntype functionname( argument of type T)
{

Body of function with type T wherever appropriate

}
The function template syntax is similar to that of the class template except that we are defining functions instead of classes. We must use the template parameter T as and when necessary in the function body and in its argument list.
The following example declares a swap() function template that will swap two values of a given type of data.
Example:
template <>
void swap (T&a, T&b)
{
T temp = a;
a = b;
b= temp
}

This essentially declares a set of overloaded functions, one for each type of data. We can invoke the swap() function like any ordinary function. For example, we can apply the swap() function as follows:

void f(int m, int n, float a, float b)
{
swap(m,n); // swap two integer values
swap(a,b); // swap two float values
}
This will generate a swap() function from the function template for each set of argument types. Another function often used is sort() for sorting arrays of various types such as int and double. The following example shows a function template for bubble sort:

Member function Templates

When we created a class template for vector, all the member functions were defined as inline which was not necessary. We could have defined them outside the class as well. But remember that the member functions of the template classes themselves are parameterized by the type argument (to their template classes) and therefore these functions must be defined by the function templates. It takes the following general form:

Template <>
Returntype classname <> function_name(arg list)
{
Body of the function
}


Template Arguments

A template can have multiple arguments. That is, in addition to the type argument t, we can also use other arguments such as strings, function names, constant expressions and built-in types. Consider the following example:

Template <>
class array
{
T n[size]; // automatic array initialization
};

This template supplies the size of the array as an argument. This implies that the size of the array is known to the compiler at the compile time itself. The arguments must be specified whenever a template class.

Example:

array<> n1; // array of 10 integers
array<> n2; // array of 15 floats
array<> n3; // string of size 30

The size is given as an argument to the template class. Compare this with the creation of the template class vector where the size is given as an argument to the object.

Example:

#include<>
#include<>
Void swap(int x, int y)
{
Int t;
T=x;

X=y;
Y=t;
Cout<< x << y;
}
Void main()

{
Clrscr();
Swap(15,20);
Swap(33.05,85.66);
Swap(“hello”, “world”);
}


No comments:

Post a Comment