AST21105
Object-Oriented Programming and Design
Topic 10
Templates
Lecture notes are based on textbook and various resources over the Internet

Generic Programming
2

Generic Programming
o
Such software entities are known as:
n
Parametric polymorphism
in ML, Scala, Haskell and Julia;
n
Parameterized types
in the influential book
Design Patterns
written by
Gang of Four
in 1994;
n
Generics
in Ada, C#, Delphi, Eiffel, F#, Java,
Rust, Swift, TypeScript, Visual Basic .NET;
n
Templates
in C++ and D.
3

Templates in C++
o
In C++,
templates
are the mechanism to support generic
programming.
o
There are two kinds of templates that can be defined in
C++:
n
Function templates
n
Class templates.
o
They are particularly effective mechanisms for generic
programming because they make the generalization
possible
without sacrificing efficiency
.
n
Runtime execution is not getting slower, at the cost of longer
compilation.
4

5
Function Template
o
We often find a set of functions
that look very much similar, for
example:
int
max(
int
a,
int
b)
{
if
(a > b)
return
a;
else
return
b;
}
string max(
const
string& a,
const
string& b)
{
if
(a > b)
return
a;
else
return
b;
}

6
Function Template
o
In C++, we can make a single
function definition using a feature
known as
function template
.
template <typename T>
T max(
const
T& a,
const
T& b)
{
if
(a > b)
return
a;
else
return
b;
}
Note:
- The template above is NOT a function and you CANNOT CALL IT.
- Instead, it is a generator that generates a number of functions.

7
Function Template
o
The keyword
typename
may be replaced by keyword
class
;
the following template definition is equivalent to the one on
the last page:
// No difference for writing
// <typename T> or <class T>
template <class T>
T max(
const
T& a,
const
T& b)
{
if
(a > b)
return
a;
else
return
b;
}

8
Function Template
o
The compiler creates functions using function templates.
n
In this case, the compiler creates two different max()
functions using the function template above.
o
This is called
template instantiation
.
n
Analogy: Just as instantiation of a class results in an object,
instantiation of a function template results in a function.
int
i = 2, j = 3;
// create a max function with T = int
cout << max(i,j);
string a("Hello"), b("World");
// create a max function with T = string
cout << max(a, b);

9
Function Template
o
The parameter T in the template definition is called a
template
parameter
.
