DM560, Introduction to Programming in C++

Sheet 10

Task 1

This is the Drill for Chapter 19 on page 707.

  1. Define template<typename T> struct S { T val; };.
  2. Add a constructor, so that you can initialize with a T.
  3. Define variables of types S<int>, S<char>, S<double>, S<string>, and S<vector<int>> ; initialize them with values of your choice.
  4. Read those values and print them.
  5. Add a function template get() that returns a reference to val.
  6. Put the definition of get() outside the class.
  7. Make val private.
  8. Do 4 again using get().
  9. Add a set() function template so that you can change val.
  10. Replace set() with an S<T>::operator=(const T&). Hint: Much simpler than §19.2.5.
  11. Provide const and non-const versions of get().
  12. Define a function template<typename T> read_val(T& v) that reads from cin into v.
  13. Use read_val() to read into each of the variables from 3 except the S<vector<int>> variable.
  14. Bonus: Define input and output operators ( >> and << ) for vector<T> s. For both input and output use a { val, val, val } format. That will allow read_val() to also handle the S<vector<int>> variable. Remember to test after each step.

Task 2

Exercise 2 of Chapter 19 on page 709.

Write a template function that takes a vector<T> vt and a vector<U> vu as arguments and returns the sum of all vt[i]*vu[i]s.

Task 3

Exercise 3 of Chapter 19 on page 709.

Write a template class Pair that can hold a pair of values of any type. Use this to implement a simple symbol table like the one we used in the calculator (§7.8).

Task 4

Exercise 10 of Chapter 19 on page 709.

Implement a simple unique_ptr supporting only a constructor, destructor, –>, *, and release(). In particular, don’t try to implement an assignment or a copy constructor.

Task 5

Exercise 11 of Chapter 19 on page 709.

Design and implement a counted_ptr<T> that is a type that holds a pointer to an object of type T and a pointer to a “use count” (an int) shared by all counted pointers to the same object of type T. The use count should hold the number of counted pointers pointing to a given T. Let the counted_ptr’s constructor allocate a T object and a use count on the free store. Let counted_ptr’s constructor take an argument to be used as the initial value of the T elements. When the last counted_ptr for a T is destroyed, counted_ptr’s destructor should delete the T. Give the counted_ptr operations that allow us to use it as a pointer. This is an example of a “smart pointer” used to ensure that an object doesn’t get destroyed until after its last user has stopped using it. Write a set of test cases for counted_ptr using it as an argument in calls, container elements, etc.