S R T B H P N

Chapter-4 Exercises


Programming exercises: Templates:
  1. Write a calculator class that provides methods for addition, subtraction, multiplication and division. Use template parameters to support those operations for all the C++ arithmetic types.
    Can you make this work for complex numbers? You will need a specialization for that. what will you do for division?
  2. Write a CircularBuffer class that has an "add" method that accepts a value of unspecified type and appends it to a private member collection - one of the STL containers. After the method has been called N times, it appends the new item and discards the oldest item, keeping the collection size at N items. Provide an iterator that starts at the most recent and increments toward the oldest.
    Is there an STL container that will make this very easy to implement? Please demonstrate that your CircularBuffer instances behave as expected.
  3. Write a numeric formatter that returns the string representation of any of the numeric types, in a field with of N characters. so, the string representation for the floating point number 3.5 in a field of 6 might appear as either "3.5   " or as "   3.5".
    Extend the formatter to work with strings, where, if the string is longer than the field width, you trucate to the first N characters, then replace the last three characters in the truncated string with "...", so my name in a field of 8 would appear as "Jim F...".
  4. Write a set of template function overloads:
      template <typename T>
      void WhoAmI(const T& t)
      {
        ...
      }
    
    that write a message to the console stating that t is one of:
    • fundamental type
    • STL sequentioal container
    • STL associative container

    The CppProperty repository has code that does this kind of function overload - look for the functions at the end of Property.h. That code depends on the contents of CustomContTypeTraits.h in that repository.