Skip to content

Teaching Notes: Module 07

  • Function templates
  • Class templates
  • Template instantiation
  • Working with any type

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;
}
  1. Returning by value instead of reference

    // WRONG for min/max - breaks when equal
    template <typename T>
    T min(T a, T b) { return (a < b) ? a : b; }
    // CORRECT
    template <typename T>
    T const& min(T const& a, T const& b) {
    return (a < b) ? a : b;
    }
  2. Not using global namespace

    • ::swap to avoid conflicts with std::swap
  • When equal, return SECOND argument (per subject)

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]);
}
  1. Not handling const arrays

    • Need overload for void (*func)(T const&)
  2. 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!

  • Default constructor (empty array)
  • Size constructor
  • Copy constructor (deep copy!)
  • Assignment operator (deep copy!)
  • Destructor
  • operator[] with bounds checking
  • size() member function
  1. Shallow copy

    // WRONG
    Array(const Array& other) : _size(other._size) {
    _array = other._array; // Points to same memory!
    }
    // CORRECT
    Array(const Array& other) : _array(NULL), _size(0) {
    *this = other;
    }
  2. Not value-initializing array

    // Default construction
    _array = new T[n](); // () = value initialization
  3. Wrong exception type

    • Use std::out_of_range or std::exception
  • Must be in header (or .tpp included by header)
  • Compiler needs to see implementation at instantiation
  • “Why can’t template implementations be in .cpp files?”
  • “What does new T[n]() do differently than new T[n]?”
  • “How do you ensure deep copy in assignment operator?”