![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
void swap (int& a, int& b) {
int tmp = a;
a = b;
b = tmp;
}
If you wanted to swap other types of variables (including those you've defined) you could copy this code, replacing int by (say) float. But in situations like this, where the code is potentially generic, templates can be used.
template <class T>
void swap (T& a, T& b) {
T tmp = a;
a = b;
b = tmp;
}
Here the ``T" name is arbitrary (like a formal parameter in a function definition) and the class keyword can be replaced by the newer typename keyword. Note that the function is written much as before. When the compiler is now given the following code
int a = 3, b = 5; float f=7.5, g=9.5; swap (a, b); swap (f, g);
it will create a version (``instantiation") of swap for each type required. These versions have nothing in common except that they were created from the same template - they won't share members, not even static ones. Templates are an example of source code re-use not object code re-use.
You can have template functions, but also template classes and derived classes.