Lab 5

Topics: function templates, class templates

Getting started:


Part 1 (14:00)


Part 2 (~14:10)


Part 3 (15:20)


Part 4 (15:30)


Prep Problem 1

In file pp1.cpp write function template swap_if_bigger that swaps two elements of arbitrary but equal type if the first is bigger than the second (use operator < to decide)

Examples:

  int a=2, b=1;
  swap_if_bigger(a, b);  // now: a=1, b=2
  
  double c=0.5, d=1.3;
  swap_if_bigger(c, d);  // no change

Also write test code in main()


Prep Problem 2

In file pp2.cpp write class template Array that stores a C-array of type T and size N in place, i.e., not allocating it on the heap

Also implement the constructor that initializes all values with T(), the size function that returns the number of elements, and the bracket operator giving access to elements similar to how C-arrays work

Example:

  Array<int, 3> A1;    // int array of size 3 containing 0s
  Array<double, 5> A2; // double array of size 5 containing 0s
  cout << A1.size() << endl; // 3
  cout << A2.size() << endl; // 5
  A1[0] = 2;
  cout << A1[0] << endl;     // 2                       

Prep Problem 3

Transform the singly connected list implementation that works for int data (given in SList.h, SList.cpp, and SListMain.cpp) into a class template for arbitrary data payload

The class template must be implemented in file SListTemplate.h and tested using SListTemplateMain.cpp


Prep Solutions

Lab Exercise

Secrets