2.3.1 Function templates

Consider the following function:


void swap (int& a, int& b) {
   int tmp = a;
   a = b;
   b = tmp;
}

Swapping integers. This function let's you swap the contents of two integer variables. But when programming quite a big application, it is probable that you have to swap float, long or char variables, or even shape variables - as defined in section 2. So, an obvious thing to do would be to copy the piece of code (cut-n-paste!) and to replace all ints by shapes, wouldn't it?

A drawback of this solution is the number of similar code pieces, that have to be administered. Additionally, when you need a new swap function, you must not forget to code it, otherwise you get a compile-time error. And now imagine the overhead when you decide to change the return type from void to int to get information, if the swap was successful - the memory could be too low to create the local tmp variable, or the assignment operator (see shape) could not be defined. You would have to change all x versions of swap - and go insane...

Templates or Parametrized types. The solution to this dark-drawn scenario are templates, template functions are functions that are parametrized by at least one type of their arguments:


template <class T>
void swap (T& a, T& b) {
   T tmp = a;
   a = b;
   b = tmp;
}

Note that the T is an arbitrary type-name, you could use U or anyType as well. The arguments are references to the objects, so the objects are not copied to the stack when the function is called. When you write code like


int a = 3, b = 5;
shape MyShape, YourShape;
swap (a, b);
swap (MyShape, YourShape);

the compiler "instantiates" the needed versions of swap, that means, the appropriate code is generated. There are different template instantiation techniques, for example manual instantiation, where the programmer himself tells the compiler, for wich types the template should be instantiated.

Function template examples. Other examples for function templates are:


template <class T> 
T& min (T& a, T&b) { return a < b ? a : b; }

template <class T>
void print_to_cout (char* msg, T& obj) {
   cout << msg << ": " << obj << endl;
}

To use the last template function, objects given as the second argument must have the operator<< defined, otherwise you will get a compile-time error.

Continue with section 2.3.2

Back to index


Johannes Weidl (J.Weidl@infosys.tuwien.ac.at) - Apr 16, 1996