Templated functions
When you write library code, you often have to write several functions that differ only between the types that are passed to the function; the routine action is the same, it's just the types that have changed. C++ provides templates to allow you to write more generic code; you write the routine using a generic type and at compile time the compiler will generate a function with the appropriate types. The templated function is marked as such using the template keyword and a list of parameters in angle brackets (<>) that give placeholders for the types that will be used. It is important to understand that these template parameters are types and refer to the types of the parameters (and return a value of the function) that will be replaced with the actual types used by calling the functions. They are not parameters of the function, and you do not (normally) provide them when you call the function.
It is best to explain template functions with an example. A simple maximum function can be written like this:
int maximum(int lhs, int rhs)
{
return (lhs > rhs) ? lhs : rhs;
}
You can call this with other integer types, and smaller types (short, char, bool, and so on) will be promoted to an int, and values of larger types (long long) will be truncated. Similarly, variables of unsigned types will be converted to the signed int which could cause problems. Consider this call of the function:
unsigned int s1 = 0xffffffff, s2 = 0x7fffffff;
unsigned int result = maximum(s1, s2);
What is the value of the result variable: s1 or s2? It is s2. The reason is that both values are converted to signed int and when converted to a signed type s1 will be a value of -1 and s2 will be a value of 2147483647.
To handle unsigned types, you need to overload the function and write a version for signed and unsigned integers:
int maximum(int lhs, int rhs)
{
return (lhs > rhs) ? lhs : rhs;
}
unsigned maximum(unsigned lhs, unsigned rhs)
{
return (lhs > rhs) ? lhs : rhs;
}
The routine is the same, but the types have changed. There is another issue--what if the caller mixes types? Does the following expression make any sense:
int i = maximum(true, 100.99);
This code will compile because a bool and a double can be converted to an int and the first overload will be called. Since such a call is nonsense, it would be much better if the compiler caught this error.