Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
A template function is a function with template arguments.
Suppose you want to write a function that returns the absolute value of a number, for both int and double. The absolute value of a number is its value without regard to its sign: The absolute value of 3 is 3 and the absolute value of -3 is also 3.
These functions could be written like below:
int Abs(const int n) |
double Abs(const double n) |
The body of these are identical, yet for every data type you will need to write a different function.
Instead, a template function can be used:
template <class T> |
Note that this example is similar to std::abs.
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.