Function Templates

Introduction

  • Function templates are functions that serve as a pattern for creating other similar functions.
  • You create a function without having to specify the exact type(s) of some or all the variables. Instead you define the function using placeholder types, called template type parameters.
  • Use function templates to write generic functions that be be used with arbitrary types.

Creating Function templates

Example

template <typename Type> // template parameter declaration
Type max(Type tX, Type tY)
{
  return (tX > tY) ? tX : tY;
}
 
int main()
{
  int nValue = max(3,7); //returns 7
  double dValue = max(6.34, 22.11); // returns 22.11
  char chValue = max('a', '6'); // returns 'a'
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.