CS 162 Lecture Notes - Lecture 20: Standard Template Library
CS 162 – Lecture 20 – Templates
Function Templates
o We hae a geeral algorith hich does’t chage ee if types chage
o Algorithm Abstraction: expressing algorithms in a very general way so that we
can ignore incidental detail and concentrate on the substantive part of the
algorithm
o Example:
▪ Swap
o Make a template function which can take any type
▪ Template <class T>
▪ Void swap(T& v1, T& v2){
• T temp;
• Temp = v1;
• V1 = v2;
• V2 = temp;
▪ }
Details
o Template <class T>
▪ Referred to as the template prefix
▪ Tells the compiler that the definition that follows is a template
▪ T is a type parameter
o Template definition is a large collection of function definitions
o Compiler does not actually produce definitions for every single type
o One will be produced for every type which uses the template in the program
o Compilers are not consistent in their treatment of templates
▪ Needs to be defined in the same file it is invoked
▪ .hpp
Templated Classes
o Work the same way as templated functions
find more resources at oneclass.com
find more resources at oneclass.com
o All functions within the class will operate on the provided types
o Scope with ClassName<T>::functionname()
o Each function needs the Template prefix
Vector: and Example of a Templated Class
o Arrays that can grow and shrink in length while the program is running
o Formed from template class in the Standard Template Library
o Has a base type and stores a collections of this base type
▪ Vector <int> v;
o Still starts indexing at zero, can still use hard brackets to access things
o Use push_back to add one element to the end
o Number of elements ==size
o How much memory currently allocated == capacity
▪ When capacity is greater than or equal to size
• Typically doubles when size is greater than capacity
Demo (code taken from instructor)
find more resources at oneclass.com
find more resources at oneclass.com