Export (0) Print
Expand All

Function Templates

Class templates define a family of related classes that are based on the parameters passed to the class upon instantiation. Function templates are similar to class templates, but define a family of functions. With function templates, you can specify a set of functions that are based on the same code, but act on different types or classes. Here is a function template that swaps two items:

// function_templates1.cpp
template< class T > void MySwap( T& a, T& b )
   T c;
   c = a; a = b; b = c;
int main()

This code defines a family of functions that swap their parameters. From this template you can generate functions that will swap not only int and long types, but also user-defined types. MySwap will even swap classes if the class's copy constructor and assignment operator are properly defined.

In addition, the function template will prevent you from swapping objects of different types, because the compiler knows the types of the a and b parameters at compile time.

Although this function could be performed by a nontemplated function, using void pointers, the template version is type-safe. Consider the following calls:

int j = 10;
int k = 18;
CString Hello = "Hello, Windows!";
MySwap( j, k );          //OK
MySwap( j, Hello );      //error

The second MySwap call triggers a compile-time error, since the compiler cannot generate a MySwap function with parameters of different types. If void pointers were used, both function calls would compile correctly, but the function would not work properly at run time.

Explicit specification of the template arguments for a function template is allowed. For example:

// function_templates2.cpp
template<class T> void f(T) {}
int main(char j) {
   f<int>(j);   //generate the specialization f(int)

When the template argument is explicitly specified, normal implicit conversions are done to convert the function argument to the type of the corresponding function template parameters. In the above example, the compiler will convert (char j) to type int.

What do you want to know more about?

See Also


© 2014 Microsoft