Skip to content

Module 07 Solutions

Download Module 07 Solutions

Simple function templates.

whatever.hpp
template <typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
template <typename T>
T const& min(T const& a, T const& b) {
return (a < b) ? a : b; // Return second if equal
}
template <typename T>
T const& max(T const& a, T const& b) {
return (a > b) ? a : b; // Return second if equal
}

Apply function to each element.

iter.hpp
template <typename T>
void iter(T* array, size_t length, void (*func)(T&)) {
for (size_t i = 0; i < length; i++)
func(array[i]);
}
// Const version
template <typename T>
void iter(T* array, size_t length, void (*func)(T const&)) {
for (size_t i = 0; i < length; i++)
func(array[i]);
}
main.cpp
template <typename T>
void print(T const& elem) {
std::cout << elem << std::endl;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
iter(arr, 5, print<int>); // Must specify type
}

Full class template with bounds checking.

Array.hpp
template <typename T>
class Array {
private:
T* _array;
unsigned int _size;
public:
Array() : _array(NULL), _size(0) {}
Array(unsigned int n) : _array(new T[n]()), _size(n) {}
Array(const Array& other) : _array(NULL), _size(0) {
*this = other;
}
Array& operator=(const Array& other) {
if (this != &other) {
delete[] _array;
_size = other._size;
_array = new T[_size];
for (unsigned int i = 0; i < _size; i++)
_array[i] = other._array[i];
}
return *this;
}
~Array() {
delete[] _array;
}
T& operator[](unsigned int index) {
if (index >= _size)
throw std::out_of_range("Index out of bounds");
return _array[index];
}
const T& operator[](unsigned int index) const {
if (index >= _size)
throw std::out_of_range("Index out of bounds");
return _array[index];
}
unsigned int size() const {
return _size;
}
};

Key Points:

  • Template implementation must be in header
  • new T[n]() value-initializes elements
  • Deep copy in both copy constructor and assignment
  • Bounds checking with exception