Concordia University
Department of Computer Science and
Software Engineering
COMP345 – Advanced Program Design
with C++
Lecture 10: Templates
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-1
Learning Objectives
 Function Templates
 Class Templates
 Vectors
 Iterators
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-2
Introduction
 C++ templates
 Allow very "general" definitions for functions and classes
 Type names are "parameters" instead of
actual types
 Precise definition determined at run-time
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-3
Function Templates
 Typical function swapValues:
void swapValues(int& var1, int& var2)
{
int temp;
temp = var1;
var1 = var2;
var2 = temp;
}
 Applies only to variables of type int
 But code would work for any types!
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-4
Function Templates vs. Overloading
 Could overload function for char’s:
void swapValues(char& var1, char& var2)
{
char temp;
temp = var1;
var1 = var2;
var2 = temp;
}
 But notice: code is nearly identical!
 Only difference is type used in 3 places
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-5
Function Template Syntax
 Allow "swap values" of any type variables:
template<class T>
void swapValues(T& var1, T& var2)
{
T temp;
temp = var1;
var1 = var2;
var2 = temp;
}
 First line called "template prefix"
 Tells compiler what’s coming is "template"
 And that T is a type parameter
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-6
Template Prefix
 Recall:
template<class T>
 In this usage, "class" means "type", or
"classification"
 Can be confused with other "known" use
of word "class"!
 C++ allows keyword typename in place of
keyword class here
 But most use class anyway
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-7
Template Prefix
 Again:
template<class T>
 T can be replaced by any type
 Predefined or user-defined (like a C++ class type)
 In function definition body:
 T used like any other type
 Note: can use other than T, but T is
"traditional" usage
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-8
Function Template Definition
 swapValues() function template is actually
large "collection" of definitions!
 A definition for each possible type!
 Compiler only generates definitions when
required
 But it’s "as if" you’d defined for all types
 Write one definition  works for all types
that might be needed
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-9
Calling a Function Template
 Consider the following call:
swapValues(int1, int2);
 C++ compiler "generates" function definition for two int
parameters
using template
 Likewise for all other types
 Needn’t do anything "special" in call
 Required definition automatically generated
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-10
Calling a Function Template
//Program to demonstrate a function template.
#include <iostream>
using std::cout;
using std::endl;
int main( )
{
int integer1 = 1, integer2 = 2;
cout << "Original integer values are "
<< integer1 << " " << integer2 << endl;
//Interchanges the values of
//variable1 and variable2.
//The assignment operator
//must work for the type T.
swapValues(integer1, integer2);
cout << "Swapped integer values are "
<< integer1 << " " << integer2 << endl;
template<class T>
void swapValues(T& variable1, T& variable2)
{
T temp;
char symbol1 = 'A', symbol2 = 'B';
cout << "Original character values are: "
<< symbol1 << " " << symbol2 << endl;
temp = variable1;
variable1 = variable2;
variable2 = temp;
swapValues(symbol1, symbol2);
}
cout << "Swapped character values are: "
<< symbol1 << " " << symbol2 << endl;
return 0;
}
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-11
Compiler Complications
 Function declarations and definitions
 Typically we have them separate
 For templates  not supported on
most compilers!
 Safest to place template function
definition in file where invoked
 Many compilers require it appear 1st
 Often we #include all template definitions
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-12
More Compiler Complications
 Check your compiler’s specific requirements
 Some need to set special options
 Some require special order of arrangement
of template definitions vs. other file items
 Most usable template program layout:
 Template definition in same file it’s used
 Ensure template definition precedes all uses
 Can #include it
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-13
Multiple Type Parameters
 Can have:
template<class T1, class T2>
 Not typical
 Usually only need one "replaceable" type
 Cannot have "unused"
template parameters
 Each must be "used" in definition
 Error otherwise!
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-14
Algorithm Abstraction
 Refers to implementing templates
 Express algorithms in "general" way:
 Algorithm applies to variables of any type
 Ignore incidental detail
 Concentrate on substantive parts
of algorithm
 Function templates are one way C++
supports algorithm abstraction
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-15
Defining Templates Strategies
 Develop function normally
 Using actual data types
 Completely debug "ordinary" function
 Then convert to template
 Replace type names with type parameter
as needed
 Advantages:
 Easier to solve "concrete" case
 Deal with algorithm, not template syntax
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-16
Inappropriate Types in Templates
 Can use any type in template for which
code makes "sense"
 Code must behave in appropriate way
 e.g., swapValues() template function
 Cannot use type for which assignment operator isn’t defined
 Example: an array:
int a[10], b[10];
swapValues(a, b);
 Arrays cannot be "assigned"!
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-17
Class Templates
 Can also "generalize" classes
template<class T>
 Can also apply to class definition
 All instances of T in class definition replaced by type
parameter
 Just like for function templates!
 Once template defined, can declare
objects of the class
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-18
Class Template Definition
template<class T>
class Pair
{
public:
Pair();
Pair(T firstVal, T secondVal);
void setFirst(T newVal);
void setSecond(T newVal);
T getFirst() const;
T getSecond() const;
private:
T first; T second;
};
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-19
Template Class Pair Members
template<class T>
Pair<T>::Pair(T firstVal, T secondVal)
{
first = firstVal;
second = secondVal;
}
template<class T>
void Pair<T>::setFirst(T newVal)
{
first = newVal;
}
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-20
Template Class Pair
 Objects of class have "pair" of values of
type T
 Can then declare objects:
Pair<int> score;
Pair<char> seats;
 Objects then used like any other objects
 Example uses:
score.setFirst(3);
score.setSecond(0);
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-21
Pair Member Function Definitions
 Notice in member function definitions that use a
template parameter type:
 Each definition is itself a "template"
 Requires template prefix before
each definition
 Class name before :: is Pair<T>
 Not just "Pair"
 But constructor name is just "Pair"
 Destructor name is also just "~Pair"
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-22
Class Templates as Parameters
 Consider:
int addUP(const Pair<int>& the_Pair);
 The type (int) is supplied to be used for T
in defining this class type parameter
 It "happens" to be call-by-reference here
 Again: template types can be used
anywhere standard types can
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-23
Class Templates
Within Function Templates
 Rather than defining new overload:
template<class T>
T addUp(const Pair<T>& the_Pair);
//Precondition: Operator + is defined for values of type T
//Returns sum of two values in the Pair
 Function now applies to all kinds of numbers
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-24
Restrictions on Type Parameter
 Only "reasonable" types can be substituted
for T
 Consider:
 Assignment operator must be "well-behaved"
 Copy constructor must also work
 If T involves pointers, then destructor must
be suitable!
 Similar issues as function templates
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-25
Type Definitions
 Can define new "class type name"
 To represent specialized class template name
 Example:
typedef Pair<int> PairOfInt;
 Name PairOfInt now used to declare
objects of type Pair<int> :
PairOfInt pair1, pair2;
 Name can also be used as parameter,
or anywhere else type name allowed
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-26
Friends and Templates
 Friend functions can be used with
template classes
 Same as with ordinary classes
 Simply requires type parameter
where appropriate
 Very common to have friends of
template classes
 Especially for operator overloads (as
we’ve seen)
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-27
Templates and Inheritance
 Nothing new here
 Derived template classes
 Can derive from template or non-template class
 Derived class is then naturally also a template class
 Syntax same as ordinary class derived
from ordinary class
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-28
Vectors
 Vector Introduction
 Recall: arrays are fixed size
 Vectors: "arrays that grow and shrink"
 During program execution
 Defined in Standard Template Library(STL)
 Using template class
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-29
Vector Basics
 Similar to array:
 Has base type
 Stores collection of base type values
 Declared differently:
 Syntax: vector<Base_Type>
 Indicates template class
 Any type can be "plugged in" to Base_Type
 Produces "new" class for vectors with that type
 Example declaration:
vector<int> v;
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-30
Vector Use
#include <vector>
using namespace std;
 Vector template class is defined in the vector library in
namespace std
vector<int> v;
 declares an empty vector of integers named v. In order to
initialize a vector, one has to rely on the constructor :
vector<int> v(10);
 declares a vector of 10 integers, all initialized to 0. Note that if
one wants to create an initialized vector of values of a userdefined type, such as in:
vector<MyClass> v(10);
 then the default constructor for MyClass must properly (allocate
and) initialize the data members of the class.
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-31
Vector Use
 The elements of the vector are referred to using the standard square




brackets array notation:
v[i]
The square brackets notation can be used to refer to existing elements,
but cannot be used to initialize new elements. In order to add new
elements after initialization:
vector<int> v;
v.push_back(42);
Once an element has been initialized either through declaration or
through the push_back() method, it can be assigned other values
using the square bracket notation.
The vector class template also provides a size() method that returns
the number of elements in the vector. That crucial information allows
you (for example) to loop through a vector:
for(int i = 0; i < v.size(); i++) cout << v[i] <<
endl;
Note that using the square brackets notation to refer to an element out
of the initialized bounds of the vector will result in erratic program
behavior, as with dereferencing wild pointers (which it is, in fact, due to
the internal pointer implementation of vector).
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-32
Vector Use
 You can use the overloaded = (assignment) operator to assign one




vector to another, for example
v1 = v2
so long as they are vectors of the same type (e.g. both vector<int>
or vector<double> ). In this case the contents of v1 are overwritten
with the contents of v2 and v1 is truncated or extended to be the same
length as v2.
You might also consider using the at() function in preference to the
square brackets.
v.at(92)
is the same as
v[92]
except that it will terminate the program if v[92] does not exist,
whereas v[92] will result in erratic program behavior.
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-33
Vector Example:
Display 7.7 Using a Vector (1 of 2)
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-34
Vector Example:
Display 7.7 Using a Vector (2 of 2)
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-35
Two-dimensional vectors





A two-dimensional vector in C++ is just a vector of vectors. For example, you could define a
two-dimensional vector of integers as follows:
 vector<vector<int> > v2;
Note the space between <int> and the second >. If you have them next to each other, as in
>>,the compiler interprets it as an operator and flags it as an error. This definition gives you
an empty two-dimensional vector. If you wanted to grow it with push_back(), you would
have to push back a one-dimensional vector, not a single int. For example:
 vector<int> v(5);
v2.push_back(v);
To initialize a two-dimensional vector to be of a certain size, you first have to initialize a onedimensional vector and then use this to initialize the two-dimensional one:
 vector<int> v(5);
vector<vector<int> > v2(8,v);
You can picture v2 as a two-dimensional vector consisting of eight rows with five integers in
each row. You may refer to individual elements of a two-dimensional vector by using two
subscripts; the following sets the third element of the fifth row of v2 to 99:
 v2[4][2] = 99; // first element of the first row is v2[0][0]
The following procedure would display a two-dimensional vector of int:

void display (const vector<vector<int> >& vy)
{ for (int i = 0; i < vy.size(); i++)
{ for (int j = 0; j < vy[i].size(); j++)
cout << vy[i][j] << " ";
cout << endl;
}
}
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-36
Vectors: pitfalls
 a vector's well behavior depends on the well-behaved
definition of the vector's base type
 Constructors, assignment, copy
 The square bracket notation on vectors does not
perform boundary checking
 The at() member function does
 As much as possible, vectors should be passed as
references
 Avoid proliferation of vectors, as they are memory-
consumptive
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-37
Other containers as template classes
 list: doubly-linked list
 slist: single-linked list
 deque: double-ended queue
 Adapter template classes from deque
 queue: single-ended queue (LILO)
 stack: LIFO stack
 map: functional associative container
 set: aggregation without repetition
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-38
Iterators
 Each of the STL container classes has its own type of
iterator.
 An iterator is a construct that allows you to cycle
through the data items stored in a container class
 Generalization of a pointer
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-39
Iterators
 Uniform use across container classes
 ++, -- : moving to the next/previous element
 ==, != : testing if two iterators are pointing to the same
element or not
 * (dereferencing) : allowing to access the data “pointed to”
by the iterator
 c.begin() : returns an iterator that points to the first
element of the container c
 c.end() : returns an iterator that corresponds to the endmarker of the container c (i.e. after the last element)
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-40
Display 19.1
Iterators Used with a Vector (1 of 2)
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-41
Display 19.1
Iterators Used with a Vector (2 of 2)
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-42
Kinds of Iterators
 Different containers have different access behavior
 Forward-only (only ++)
 Bidirectional (++ and --)
 Random access (++, --, [])
 When using a constant iterator, its dereferenced
element is constant, i.e. cannot be assigned a new
value
 Reverse iterators allow to iterate from c.end() to
c.begin(), referred to as c.rbegin() and
c.rend()
 Problem: c.end() is a sentinel, not a regular iterator, it
cannot be incremented/decremented
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-43
Forward/reverse iterators
int main( )
{
vector<char> container;
container.push_back('A');
container.push_back('B');
container.push_back('C');
//Program to demonstrate a reverse iterator.
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
using std::vector<char>::iterator;
using std::vector<char>::reverse_iterator;
cout << "Forward:\n";
iterator p;
for (p = container.begin( ); p != container.end( ); p++)
cout << *p << " ";
cout << endl;
cout << "Reverse:\n";
reverse_iterator rp;
for (rp = container.rbegin( ); rp != container.rend( ); rp++)
cout << *rp << " ";
cout << endl;
return 0;
}
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-44
Iterator class : example
template<class T>
class Node {
public:
Node(T theData, Node<T>* theLink) : data(theData), link(theLink){}
Node<T>* getLink( ) const { return link; }
const T getData( ) const { return data; }
void setData(const T& theData) { data = theData; }
void setLink(Node<T>* pointer) { link = pointer; }
private:
T data;
Node<T> *link;
};
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-45
Iterator class : example
template<class T>
class ListIterator {
public:
ListIterator( ) : current(NULL) {}
ListIterator(Node<T>* initial) : current(initial) {}
const T operator *( ) const
{ return current->getData( );
ListIterator operator ++( ) //Prefix form
{ current = current->getLink( );
return *this; }
bool operator ==(const ListIterator& rightSide) const
{ return (current == rightSide.current); }
private:
Node<T> *current; };
#endif //ITERATOR_H
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-46
Drawbacks to templates
 Many compilers have poor support for templates, or use differing syntax
(e.g. iterators), so the use of templates can make code less portable.
 Most compilers produce confusing error messages when errors are
detected in template code, due to the fact that the executed code is
generated by the compiler and does not appear in the original code.
This can make templates difficult to develop and fix.
 Each use of a template may cause the compiler to generate extra code
(an instantiation of the template), so the indiscriminate use of templates
can lead to code bloat, resulting in excessively large executables.
 Separate compilation of template definitions and template function
declarations is not yet implemented in most compilers, resulting in the
programmer having to place template function definitions in the same
file where the template function is invoked. This can be solved by
putting the template definition in an implementation file and #include it
in any other implementation file that uses this template. This solution is
an exception to the general rules governing the use of header files
and program files in separate compilation.
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-47
Summary
 Function templates
 Define functions with parameter for a type
 Class templates
 Define class with parameter for subparts of class
 Predefined vector and basic_string
classes are template classes
 Many container template classes are available, along
with various iterators
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet
9-48