Chapter 17: Advanced C++ Topics II

Lecture Goals

Templates

Syntax 17.3: Template Class Definition

template<typename type_variable>
class class_name
{

features
};
Example:
template<typename T>
class Pair
{
public:
Pair(T a, T b);
T get_first() const;
T get_second() const;
private:
T first;
T second;
};
Purpose: Define a class template with a type parameter.

Syntax 17.4: Template Member Function Definition

template<typename type_variable>
return_type class_name<type_variable>::function_name(parameters) constopt
{

statements
}
Example:
template<typename T>
T Pair<T>::get_first() const
{
return first;
}
Purpose: Supply the implementation of a member function for a class template.

Templates (pairs.cpp)

template<typename T>
class List {
public:
List();
void push_back(T s);
void insert(Iterator<T> pos, T s);
void erase(Iterator<T> pos);
Iterator<T> begin();
Iterator<T> end();
private:
Node<T>* first;
Node<T>* last;
};
class List {
public:
List();
void push_back(string s);
void insert(Iterator pos, string s);
Iterator erase(Iterator pos);
Iterator begin();
Iterator end();
private:
Node* first;
Node* last;
};

Templates (list.cpp)


Nested Classes

Syntax 17.5 : Nested Class Declaration

class Outer_class_name
{

...
class Nested_class_name
{
...
};
...

}
Example:
class List
{
...
class Iterator
{
...
};
};
Purpose: Define a class whose scope is contained in the scope of another class.