CIS 29 - Notes for Tuesday, 2/16

Announcements and Reminders

Recording

Function Templates

  • A function template is a pattern for a function
  • Also called a generic function
  • When instantiated it produces a template function
  • Function templates are often placed in a header file
  • A function template, by itself, is not compiled.  It doesn't get compiled until it is instantiated
Why write a function template?

Replace overloaded functions, like this:

    int         max(int n1,int n2);
   float       max(float n1,float n2);
   double      max(double n1 ,double n2);
   long        max(long n1,long n2);
   char        max(char n1,char n2);
   my_type     max(my_type n1,my_type n2);
 

The logic for each function would be the same:

{
  return a > b ? a : b ;
}

Examples

Example 13-1 - First Function Template Example

Example 13-2 - Function Template and an overloaded function

Example 13-3 - A Function Template that always returns a double

Example 13-4 - A Function Template with an array argument

Example 13-5 - A Function Template using two types

Example 13-6 - A Function Template with a user-defined type

Example 13-7 - A Function Template in a header file


Class Templates

  • A class template is a pattern for a class
  • Also called a generic class
  • When instantiated it produces a template class
  • To instantiate it, you have to provide a type
  • Class templates are often placed in a header file
  • A class template, by itself, is not compiled.  It doesn't get compiled until it is instantiated

Examples

Example 13-8 - First Class Template Example

Example 13-9 - Class Template: a generic array

Example 13-10 - A container and iterator class template

Example 13-11 - Generic File I/O

Example 13-12 - A Generic Linked List

SFML Class Templates

sf::Vector2<T>

sf::Rect<T>