Previous Slide Template Functions Next Slide

A better approach would be to write a template function. We can write the code once and use it with different types of things.

The definition of a template function depends on an underlying data type. For example:

template <class Type> 
Type maximum(Type a, Type b) 
{ 
  if (a > b) 
    return a; 
  else 
    return b; 
} 

The first line is the template prefix, which tells the compiler that Type is a data type that will be filled in later. The "unspecified type" Type is called the template parameter.


BU CAS CS - Templates
This page created by Jonathan Alon <jalon@cs.bu.edu>.
Material adapted from the textbook "Data Structures and Other Objects Using C++", by Main and Savitch.
Modified by Robert I. Pitts <rip@bu.edu>