Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) template function

 

A template function is a function with template arguments.

 

 

 

 

 

Example: abs

 

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)
{
  return (n < 0 ? -n : n);
}

 

double Abs(const double n)
{
  return (n < 0 ? -n : 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>
T Abs(const T n)
{
  return (n < 0 ? -n : n);
}

 

Note that this example is similar to std::abs.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict