Templates
31 Oct 07, 10:45AM
Templates
Templates are one of the most powerful, yet seemingly unknown, programming techniques to arise in recent years.
Very simply, templates allow you to write functions that have variable parameter types. We are all used to the idea of creating function with one or more arguments, with each argument holding a range of possible value(s). With templates, your function can also have variable argument types as well.
Functions that use templates are distinct from regular functions, and are often called 'template functions'.
When Should They Be Used
Often people are introduced to templates, by designing the MAX macro as a template. I still use the MAX macro quite happily, so I've always felt a better example of template power is a 'swap' function, which will swap the values within two variables (passed by reference) depending on which is larger, i.e.swap(10,11) => 10,11 swap(11,5) => 5,11The function for doing this is simply:
void swap(int &a, int &b) { if(a>b) { int c=a; a=b; b=c; } }However, you'll invariably find that also want to 'swap' other variable types, i.e:
swap(10.2,45.3); // using doubles swap('a','b'); // using chars swap(string("fred"),string("harry")); // using std::stringYou can off course rewrite the function n times, overloading the function to account for every possible usage, remembering as you go that each argument must have the same type. To solve this, we use templates.
template <class T> swap(T &a, T &b) { if(a>b) { T c=a; a=b; b=c; } }Drop this function into a header file (.h) somewhere, and whenever you want to swap values if one is larger than the other, you can. The important pieces of this code are really just
template <class T>when 'class', should be confused with objects or anything else is OOP, but is there to represent any type (like a variant in VB), such that 'T' is any type, but critically always the same type in each instansiation of the function. Effectively the compiler will identify the type T that is being passed to the function, and simple replace every instance of T with that type. As such our swap function will accept any type, so long as 'a' and 'b' are off the same type. For example:
swap(10.2,45.3); // T become a float or double swap('a','b'); // T become a char swap(string("fred"),string("harry")); // T becomes a std::stringOften you could write these functions using macros (#define's), however the great thing about templates over #defines is that do type checking. So it would be illegal to call out swap function with:
swap('a',45.6); swap(string("jim"), 20);