Template introduction

When you want to perform the exact same task on different types of data, you can use a template function. A good example of when this makes sense is when you are swapping two pieces of memory. The type is irrelevant, the operation is the same: save one of them in a temporary location, set that one to the second one, and set the second one to what was saved in temp.

If we write it for ints, it looks like (I call it myswap since there is a "swap" routine in a C++ library
main() {
   int i = 10, j = 20;
   myswap(i, j);          // after call want i to hold 20, j to hold 10

void myswap(int& num1, int& num2) {
   int temp = num1;
   num1 = num2;
   num2 = temp;
To have it work for any types, the int needs to be generalized. Think of this as paramaterizing the type. It's just like parameter variables that get passed in, but the type is passed in as opposed to the value. Use the keyword template and typename as in the following example.
template < typename TheType >
void myswap(TheType& val1, TheType& val2) {
   TheType temp;
   temp = val1;
   val1 = val2;
   val2 = temp;
The template line is part of the function prototype line, but it is generally formatted on two lines for readability. Now when you swap ints, the int is passed into "TheType" identifier. If you have more than one type to pass in, separate them with commas, for example
template < typename TheType1, typename TheType2 >
You can also turn classes into templates and there is the Standard Template Library (STL). Both will be discussed briefly in CSS 342.