Templates & the STL CS 2308 :: Fall 2015 Molly O'Neil
Function Templates Let's say we have a program that repeatedly needs to find the maximum value in an array In one place in our code, we need the max of an array of ints but in another place, it's an array of doubles and in a third place, it's an array of Time objects! We can declare three findmaximum() functions and duplicate a lot of code, or We can use a function template: a pattern for a function that can work with multiple data types Data types in the function are specified as parameters Compiler generates code for the function to match the specific data type(s) used where the function is called 2
Function Template Example template <class T> T findmaximum(t arr[], int size) { T max = arr[0]; // don't call this fn with size <= 0! for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; int main() { int intarr[10]; double doublearr[7]; Time timearr[5]; int imax = findmaximum(intarr, 10); double dmax = findmaximum(doublearr, 7); Time tmax = findmaximum(timearr, 5); 3
Function Template Example This function call int main() { int intarr[10]; int imax = findmaximum(intarr, 10); Causes the compiler to generate this function: int findmaximum(int arr[], int size) { int max = arr[0]; for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; 4
Function Template Example And this function call int main() { double doublearr[7]; double dmax = findmaximum(doublearr, 7); Causes the compiler to generate this function: double findmaximum(double arr[], int size) { double max = arr[0]; for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; 5
Function Template Example And this function call int main() { Time timearr[5]; Time tmax = findmaximum(timearr, 5); Causes the compiler to generate this function: Time findmaximum(time arr[], int size) { Time max = arr[0]; for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; Note that this only works because we have overloaded the < operator for the Time class! 6
More About Function Templates Function template is a pattern only; no actual code is generated until the function is called You can define a template to use multiple data types: template<class T1, class T2> Just like functions can be overloaded, function templates can be overloaded Must have unique parameter lists template <class T> T sumall(t num) template<class T1, class T2> T1 sumall(t1 num1, T2 num2) When passing a class object to a function template, be sure that all operators in the template are defined/ overloaded in the class definition! 7
Class Templates Classes can also be represented by templates A class template is a pattern for a class definition that parameterizes the type of class member variables Also called a templated class or a parameterized class An object of a templated class is a specialization When a class object is created, type information is supplied to define the type of the class member variables Object instantiation requires supplying the type name at object definition 8
Class Template Example For example, we can design a generic Linked List class as a templated class Rather than writing separate IntList, DoubleList, TimeList, SongList, etc. classes template <class T> class LinkedList { private: class Node { public: T data; Node *next; ; Node *head; public: LinkedList(); ~LinkedList(); void insert(t); void remove(t); void display(); 9
Using Class Templates Programmer passes the type information to the class template when an object of the class is instantiated: LinkedList<int> intlist; LinkedList<double> doublelist; LinkedList<Song> songlist; Once defined, the object can be treated as an ordinary object Song s1("hey Jude", "The Beatles", 2.5); songlist.insert(s1); 10
The Standard Template Library (STL) The Standard Template Library (STL) is a library containing templates for frequently used data structures and algorithms Not a part of C++ and unsupported by older compilers But standard in newer versions and commonly-used Two important types of data structures in the STL: Containers: classes that store data and impose some organization on it Iterators: mechanism for accessing elements in a container (somewhat like pointers) 11
STL Containers Sequence containers: organize and access data sequentially. E.g.: Vector An array that can dynamically change in size (by internal re-allocation). Good for insertion/removal at back; random access to elements Dequeue (pronounced "deck") A double-ended queue, usually (but not mandatorily) implemented as multiple dynamic arrays linked together internally. Good for insertion/ removal at front or back; random access to elements List A doubly-linked list. Good for insertion/removal at front or back; must iterate list for random access Associative containers: use keys to allow data elements to be quickly accessed (you'll learn more about these in Data Structures). E.g.: Set / Multiset Map / Multimap 12
STL Iterators A generalization of pointers, used to access elements of a container Five overlapping types: Forward (can be incremented, i.e. ++) Bidirectional (can also be decremented, i.e. ++ and --) Random-access (can access elements at arbitrary positions relative to the element they point to) Input (can be used in input operations with cin/istream objects) Output (can be used in output operations with cout/ostream objects) 13
STL Algorithms STL also contains algorithms implemented as function templates to perform operations on the STL containers Must #include <algorithm> Includes (among others): binary_search sort count find find_if for_each min_element max_element random_shuffle 14