Teaching Notes: Module 07
Key Learning Objectives
Section titled “Key Learning Objectives”- Function templates
- Class templates
- Template instantiation
- Working with any type
Exercise 00: swap, min, max
Section titled “Exercise 00: swap, min, max”Key Insight
Section titled “Key Insight”Templates work with ANY type that supports the required operations.
template <typename T>void swap(T& a, T& b) { T temp = a; a = b; b = temp;}Common Mistakes
Section titled “Common Mistakes”-
Returning by value instead of reference
// WRONG for min/max - breaks when equaltemplate <typename T>T min(T a, T b) { return (a < b) ? a : b; }// CORRECTtemplate <typename T>T const& min(T const& a, T const& b) {return (a < b) ? a : b;} -
Not using global namespace
::swapto avoid conflicts with std::swap
Equal Case
Section titled “Equal Case”- When equal, return SECOND argument (per subject)
Exercise 01: iter
Section titled “Exercise 01: iter”Key Concept
Section titled “Key Concept”Apply function to each element of any array type.
template <typename T>void iter(T* array, size_t length, void (*func)(T&)) { for (size_t i = 0; i < length; i++) func(array[i]);}Common Mistakes
Section titled “Common Mistakes”-
Not handling const arrays
- Need overload for
void (*func)(T const&)
- Need overload for
-
Function template as argument
template <typename T>void print(T const& elem) { std::cout << elem; }// When calling:iter(arr, 5, print<int>); // Must specify type!
Exercise 02: Array Class Template
Section titled “Exercise 02: Array Class Template”Required Features
Section titled “Required Features”- Default constructor (empty array)
- Size constructor
- Copy constructor (deep copy!)
- Assignment operator (deep copy!)
- Destructor
- operator[] with bounds checking
- size() member function
Common Mistakes
Section titled “Common Mistakes”-
Shallow copy
// WRONGArray(const Array& other) : _size(other._size) {_array = other._array; // Points to same memory!}// CORRECTArray(const Array& other) : _array(NULL), _size(0) {*this = other;} -
Not value-initializing array
// Default construction_array = new T[n](); // () = value initialization -
Wrong exception type
- Use
std::out_of_rangeorstd::exception
- Use
Template Implementation Location
Section titled “Template Implementation Location”- Must be in header (or .tpp included by header)
- Compiler needs to see implementation at instantiation
Guiding Questions
Section titled “Guiding Questions”- “Why can’t template implementations be in .cpp files?”
- “What does
new T[n]()do differently thannew T[n]?” - “How do you ensure deep copy in assignment operator?”