dinsdag 26 juni 2007

Function Templates

A function template is a generic function description; that is, it defines a function in terms of a generic type for which a specific type, such as int or double, can be substituted.
By passing a type as parameter to a template, you cause the compiler to generate a function for that particular type. Because templates let you program in terms of a generic type instead of a specific type, the process is somethimes called generic programming.
Because types are represented by parameters, the template feature is somethimes referred as parameterized types.

Function templates enable you to define a function in terms of some arbitrary type. For example, you can set up a swapping template like this:

template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}

The first line specifies that you are setting up a template and you're naming the arbitrary type Any. The keyword template and class are obligatory, except you can use the keyword typename instread of class. Also, you must use the angle brackets. The type name (Any, in this example) is your choice, as long as you follow the usual C++ naming rules; many programmers use simple names such as T. The rest of the code describes the algorithm for swapping two values of type Any. The template does not create any functions. Instead, it provides the compiler with directions about how to define a function. If you want a function to swap ints, then the compiler creates a function following the template pattern, substituting int for Any. Similarly, if you need a function to swap doubles, the compiler follows the template, substituting the double type for Any.

The keyword typename is a recent addition to C++. You can use it instead of the keyword class in this particular context. That is, you can write the template definition this way:

template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}

The typename keyword makes it a bit more obvious that the parameter Any represents a type;
however, large libraries of code have already been developed by using the older keyword class. The C++ standard treats the two keywords identically when they are used in this context.

To let the compiler know that you need a particular form of swap function, you just use a function called Swap() in your program. The compiler checks the argument types you use and then generates the corresponding function.

In a program, the template could be used as follows:

template // or typename Any
void Swap(Any &a, Any &b);

then after main(){}

// function template definition
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}

Note that function templates don't make executable programs any shorter!
The final code does not contain templates; it just contains the actual functions generated for the program. The benefits of templates are that they make generating multiple function definitions simpler and more reliable.

Geen opmerkingen: