Section 5 - Function Templates

8A.5.1 Function Templates

Besides class templates, C++ provides another kind of template,  function templates. Function templates are written when we want to create generic functions that can be used with arbitrary types. For example, one can write searching and sorting function templates that can be used with any arbitrary type. T

To perform identical operations for each type of data compactly and conveniently, use function templates. You can write a single function template definition. Based on the argument types provided in calls to the function, the compiler automatically instantiates separate object code functions to handle each type of call appropriately. The STL algorithms (like for_each()) are implemented as function templates (sometimes called template functions.)

8A.5.2 Implementing Function Templates

Function templates are implemented like regular functions, except they are prefixed  by a phrase like template <class T>, where the T can be any formal parameter.  For example, here is the prototype of a class function template for a max() function.

#include <iostream>
using namespace std;

//max returns the maximum of the two elements
template <class T>
T max(T a, T b)
{
  return a > b ? a : b;
}

8A.5.3 Using  Function Templates

Using function templates is very easy: Just use them like regular functions. When the compiler sees an instantiation of the function template -- for example, the call max(10, 15) in function main() -- it generates a function max(int, int). Similarly the compiler generates definitions for max(char, char) and max(float, float) in the following code because of the invocations of max() that it finds:.

#include <iostream>
using namespace std;

template <class T>
T max(T a, T b)
{
  return a > b ? a : b;
}
void main()
{
  cout << "max(10, 15) = " << max(10, 15) << endl;
  cout << "max('k', 's') = " << max('k', 's') << endl;
  cout << "max(10.1, 15.2) = " << max(10.1, 15.2) << endl;
}

/* ---------------- run ---------------
max(10, 15) = 15
max('k', 's') = s
max(10.1, 15.2) = 15.2
-------------------------------------- */
scenic dock on water