Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.

Similar presentations


Presentation on theme: "Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy."— Presentation transcript:

1 Chapter 3 Templates

2 Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy stuff Bugs

3 3.1 What is a Template? A template is a mechanism for writing routines that work for arbitrary types without knowing these types.  For example: Type independent algorithms and data structures Templates are most likely seen in generic algorithm implementations, i.e. sorting & searching.

4 3.2 Function Templates typedef : keyword for defining new type from an existing one. Ex: typedef double Object; Object a = 3.5; // double a = 3.5 A Function template is a design or pattern for a function which allows processors to generate an actual function from this design. A function template is not an actual function, instead it’s a design or a pattern, for what could become an actual function.

5 Function template example: Swap routine typedef double Object; void swap(Object & lhs, Object & rhs) { Object tmp = lhs; lhs = rhs; rhs = tmp; } // figure 3.1 Note: swap is part of the STL //Object: must have copy // constructor & operator= template void Swap(Object & lhs, Object & rhs) { Object tmp = lhs; lhs = rhs; rhs = tmp; }// figure 3.2

6 Swap routine used in main function: int main(){ int x =5, y = 7; double a = 2, b = 4; Swap (x,y); // swap(int,int) Swap(x,y); //reuse previous instantiation Swap(a,b); //Swap(double, double) //Swap(x, b); // illegal: no match return 0; } // figure 3.3

7 3.3 A Sorting Function Template template void insertionSort(vector &a){ for(int p = 1; p < a.size(); p++){ Comparable tmp = a[p]; int j; for(j = p; j > 0 && tmp < a[j-1]; j++) a[j] = a [j –1]; a[j] = tmp; }

8 Insertion Sort example The given insertionSort routine work for double, int, float but not char*, (primitive string), because operator “=” and “<” are undefined. sorting demo(1) sorting demo(2)

9 3.4 Class Templates A class can be a template.  Example: vector is a class template A call by value should not be used for parameters of the template type; use constant reference instead.

10 template class MemoryCell{ public: explicit MemoryCell(const Object & initVal = Object()) :storedValue(initVal){} const Object & read() const {return storedValue;} void write(const Object & x) {storedValue = x;} private: Object storedValue; }; // figure 3.8 A class template example:

11 Calling the class template from main: int main() { MemoryCell m; m.write(5); cout<<“Cell contents are ” <<m.read()<<endl; return 0; } When the interface is separated from the implementation, all member functions should be implemented as template functions

12 template class MemoryCell { public: explicit MemoryCell(const Object & initVal = Object()); const Object & read() const; const write(const Object & x); private: Object storedValue; };// figure 3.10 #include “MemoryCell.h” template MemoryCell ::MemoryCell (const Object & initVal) :storedValue(initVal){} template const Object & MemoryCell ::read() const {return storedValue;} template void MemoryCell ::write( const Object & x) {storedValue = x;} // figure 3.11 Separating the interface and implementation of the template

13 template class ClassName{ public: //public members private: //private member };// typical template interface template ReturnType ClassName ::memberName(parameterList) /*const*/ { // member body } // typical member implementation

14 Implementing the Vector Class Template Provides: Indexing, resizing, copying, and index range checking capabilities figure 3.14 vector.h figure 3.15 vector.cpp

15 3.5 Templates of Templates: A Matrix Class Figure 3.16 A complete matrix class Matrix class is represented as a vector of vectors. Overload operator [] for mutators and accessors No need for destructors, copy operator and assignment operator, (already exist in vector) Note: There must be at least a space between “>” “>” in the declaration; otherwise compilers will confuse “>>” with the shift operator. Ex: vector > array; // white space needed

16 3.6 Fancy Templates Multiple template parameters template Class Map{... }; Ex: map zipCodes; Note: class “map” is in STL

17 Default Template Parameters template Class Map{... }; Map m1; // keyType = int, valueType = int Map m2; // keyType = int, valueType = string Default template parameters are widely used in STL Note: some compilers do not support default template parameters

18 Default Template Parameters typename : a new keyword can be used instead of class template class memoryCell {... };

19 3.7 Bugs Associated with Templates Template STD changes frequently => incompatible compilers Matching algorithm breaks when template involve (function template) Nested templates are not widely supported Static functions & data members are often not handled correctly

20 Common mistakes When a class template is instantiated, all needed operations must be available.  For instance, the insertion sort template needs to have operator < defined for whatever Comparable is instantiated. Otherwise, an error will be detected at link time. Clearly state what conditions must be satisfied by the template parameters Use either reference or constant reference for parameter passing. (Page 115)

21 In class exercise Write a function template to sort three Comparable objects. When templates are used what types of errors are detected when the function template is scanned? What errors are detected when the function is instantiate? Describe syntax for class templates.

22 Summary Discussion of template facilities Template for generic algorithms


Download ppt "Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy."

Similar presentations


Ads by Google