Templates
Overloading of functions is not something that seems familiar to us. By using the overloading of functions can be created several functions that handle a process with different data types, but use the same name, for example:
void exchange (int & x, int & y)
{
int temp;
tmp = x;
x = y;
y = temp;
}
void exchange (double & x, double & y)
{
double tmp;
tmp = x;
x = y;
y = tmp;
}
Defining the function with the same name as it is none other than to facilitate the recall of a function. You simply use the same name to declare the same operation, although different data types. This is the advantage of function overloading. Its shortcomings, would not want the code to a number of functions (albeit with the same name) remains to be written.
to simplify writing of code to the problem as above C + + provides a capability called templates. By using templates, the programmer can direct the compiler to generate code in various functions of the desired data type automatically.
Creating Templates for the function
sample templates for functions are as follows:
template <class T> void exchange (T & x, T & y) {
T tmp;
tmp = x;
x = y;
y = tmp;
}
Key words template used to notify the compiler that the statement is located after the word-key is a template. After the key word there is <class T> template. After the word class that is located inside <> are identifiers. In the example above in the form T. Identification is then replace the position of defining data types in function. Note that free in the example above, the identifier T is used in the argument and also defining the variable tmp.



Leave a comment