Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers.

Similar presentations


Presentation on theme: "Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers."— Presentation transcript:

1 Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers

2 Fall 2015CISC/CMPE320 - Prof. McLeod 2 Templates - An Example Suppose you want a function that displays an array, but you don’t want to limit to just one type. Do you write overloaded versions? One each for an array of int, an array of double, an array of char, etc.? What if you want it to work for a class type, as well – suppose you had an array of string s? You don’t have a base Object type like you had in Java. The answer is to use a Template Function:

3 Fall 2015CISC/CMPE320 - Prof. McLeod 3 An Example, Cont. Prototype: template void printArray(ostream&, const T[], int); When invoked, T can be any primitive type or object type.

4 Fall 2015CISC/CMPE320 - Prof. McLeod 4 An Example, Cont. Implementation: template void printArray(ostream& out, const T data[], int size) { T value; out << "Array contents: " << endl; for (int i = 0; i < size; i++ ) { value = data[i]; if ((i + 1) % 10 == 0) out << value << endl; else out << value << '\t'; }

5 Fall 2015CISC/CMPE320 - Prof. McLeod 5 An Example, Cont. Note that you need the template line again. T is just an arbitrary name, it can be anything you want. Note the use of T in the function – standing in for a type. Now, printArray can be invoked with any type array (assuming it works with <<).

6 Fall 2015CISC/CMPE320 - Prof. McLeod 6 An Example, Cont. Invoked from main: double nums[40]; for (int i = 0; i < 40; i++) nums[i] = 0.1 * i; printArray(cout, nums, 40);

7 Fall 2015CISC/CMPE320 - Prof. McLeod 7 Template Functions, Cont. The way printArray is invoked here, the actual type is inferred from the argument at run time. If you have more than one parameter using the type T, they must end up being the same inferred type at runtime. The alternative is to specify the type when you invoke the function: printArray (cout, nums, 40);

8 Fall 2015CISC/CMPE320 - Prof. McLeod 8 Template Functions, Cont. If T will be an object type, remember to make sure that all operations carried out in the function are defined for this object. Hint: build and debug the function with a concrete type first. Error messages that result from using Templates are harder to interpret.

9 Fall 2015CISC/CMPE320 - Prof. McLeod 9 Templates vs. Polymorphism Templates supply a kind of compile-time polymorphism. Normal polymorphism is strictly a run-time process. A Template Function is a function “factory”. Functions with the necessary types are created at compile time. As a result, the use of Templates has a very low run-time cost.

10 Fall 2015CISC/CMPE320 - Prof. McLeod 10 Specialization Occurs when you have an overloaded, non- template version of the same function. If present, and the argument types match, then the non-template version will be used in preference to the template version.

11 Fall 2015CISC/CMPE320 - Prof. McLeod 11 Template Classes Another example: Suppose you need a class to store a pair of anythings… Interface: template class Pair { public: Pair(const F&, const S&); F getFirst() const; S getSecond() const; private: F first; S second; };

12 Fall 2015CISC/CMPE320 - Prof. McLeod 12 Template Classes, Cont. Just for fun, we are assuming that the two things can be of different types. Note that you can have as many typenames in the template as you want. Implementation on the next slide:

13 Fall 2015CISC/CMPE320 - Prof. McLeod 13 template Pair ::Pair(const F& a, const S& b) : first(a), second(b) {} template F Pair ::getFirst() const { return first; } template S Pair ::getSecond() const { return second; } Note how the template statement has to be repeated.

14 Fall 2015CISC/CMPE320 - Prof. McLeod 14 Template Classes, Cont. With template classes, the type cannot be inferred, you must state it explicitly. Suppose you have a function that returns the minimum and the maximum of an array at the same time. See the next slide:

15 Fall 2015CISC/CMPE320 - Prof. McLeod 15 Pair findMinMax(const double data[], const int size) { double low = data[0]; double high = data[0]; for (int i = 1; i < size; i++) { if (data[i] < low) low = data[i]; if (data[i] > high) high = data[i]; } return Pair (low, high); }

16 Fall 2015CISC/CMPE320 - Prof. McLeod 16 Reminder – typedef You might get tired of typing Pair all the time! typedef Pair PairDD; Simplifies findMinMax() a bit:

17 Fall 2015CISC/CMPE320 - Prof. McLeod 17 PairDD findMinMax(const double data[], const int size) { double low = data[0]; double high = data[0]; for (int i = 1; i < size; i++) { if (data[i] < low) low = data[i]; if (data[i] > high) high = data[i]; } return PairDD(low, high); }

18 Fall 2015CISC/CMPE320 - Prof. McLeod 18 Templates, Cont. You can also add non-type arguments to a template. Suppose you wanted to specify the size of an array to be used as T: template When used, you would have to supply a type for T and an int for the second argument: AClass aVar;

19 Fall 2015CISC/CMPE320 - Prof. McLeod 19 Templates, Cont. You can also use an argument to specify a policy. For example, the first argument is the name of an object to be sorted, the second is the name of a class that supplies the desired sort criteria for that object. Template types ignore object extension, so T can only be one type, not a derived type. If you place restrictions on what T can be, you should document them in a comment.

20 Fall 2015CISC/CMPE320 - Prof. McLeod 20 The Standard Template Library As you have probably guessed, the STL makes extensive use of Templates! See the Wikipedia entry for an overview and lots of other links. See “The Standard Template Library Programmers Guide”: http://www.sgi.com/tech/stl/index.html And links from: http://www.cplusplus.com/

21 Fall 2015CISC/CMPE320 - Prof. McLeod 21 STL Classification STL components are classified in two different ways: By Category: –Container –Iterator –Algorithm –Function Object –Utility –Adaptor –Allocator

22 Other Template Libraries The Wikipedia entry under “List of C++ template libraries” provides links to the description of 24 library projects. Fall 2015CISC/CMPE320 - Prof. McLeod 22

23 Fall 2015CISC/CMPE320 - Prof. McLeod 23 STL Classification And by Component Type: –Type (a struct or class) –Function (a global function) –Concept A Concept is part of a hierarchy of non-code descriptive rules about the restrictions on template types. Template types cannot be enforced in code, so you must rely on this documentation. A “model” is a type that passes the concept rules for a particular component.

24 Fall 2015CISC/CMPE320 - Prof. McLeod 24 STL #include s - Containers vector doubly linked list doubly ended queue queue stack associative arrays – multimap set – multiset array of booleans

25 Fall 2015CISC/CMPE320 - Prof. McLeod 25 STL #include s – General Utilities operators and pairs function objects allocators for containers C-style date and time

26 Fall 2015CISC/CMPE320 - Prof. McLeod 26 STL #include s – Iterators iterators and iterator support

27 Fall 2015CISC/CMPE320 - Prof. McLeod 27 STL #include s – Algorithms general algorithms bsearch(), qsort()

28 Fall 2015CISC/CMPE320 - Prof. McLeod 28 STL #include s – Diagnostics exception class standard exceptions assert macro C-style error handling

29 Fall 2015CISC/CMPE320 - Prof. McLeod 29 STL #include s – Strings string character classification wide character classification C-style string functions C-style wide character string functions C-style string functions ( has strlen(), strcpy(), etc.; has atof() and atoi() for string to number conversion.)

30 Fall 2015CISC/CMPE320 - Prof. McLeod 30 STL #include s – Input/Output forward declaration of I/O facilities standard iostream stuff iostream bases stream buffers input stream template output stream template manipulators string streams file streams printf() I/O stuff printf() for wide characters

31 Fall 2015CISC/CMPE320 - Prof. McLeod 31 STL #include s – Localization represent cultural differences C-style cultural differences

32 Fall 2015CISC/CMPE320 - Prof. McLeod 32 STL #include s – Language Support numeric limits C-style numeric limit macros C-style floating point limit macros dynamic memory management run-time object identification exception handling C library language support variable length function argument lists C-style stack unwinding program termination system clock C-style signal handling

33 Fall 2015CISC/CMPE320 - Prof. McLeod 33 STL #include s – Numerics complex numbers and operations numeric vectors and operations general numeric operations standard mathematical functions C-style random numbers

34 Smart Pointers Follow the “proxy pattern” Also in the STL and in Boost. For example, see auto_ptr in Memory leaks are a problem! Suppose an exception is thrown before a pointer can be deleted, and before you end the function. One answer is to only use pointers inside try blocks and make sure to have a delete statement inside the catch. (A pain!) Fall 2015CISC/CMPE320 - Prof. McLeod34

35 Smart Pointers, Cont. Another answer is to wrap a pointer in another type that controls the behaviour of the pointer: template class auto_ptr { T* ptr; public: explicit auto_ptr(T* p = 0) : ptr(p) {} ~auto_ptr() {delete ptr;} T& operator*() {return *ptr;} T* operator->() {return ptr;} //... }; Fall 2015CISC/CMPE320 - Prof. McLeod35

36 Smart Pointers, Cont. So, instead of writing: void foo() { MyClass* p = new MyClass; p->DoSomething(); delete p; } Fall 2015CISC/CMPE320 - Prof. McLeod36

37 Smart Pointers, Cont. You write: void foo() { auto_ptr p = new MyClass; p->DoSomething(); } You don’t need to make sure to have your own delete command! As soon as you are outside the scope of p, the destructor of auto_ptr is called. Fall 2015CISC/CMPE320 - Prof. McLeod37

38 Smart Pointers, Cont. With a bit more code in the smart pointer class, you can actually implement automatic garbage collection. You can avoid many common memory problems and make pointers easier to use. The STL has more implementations of smart pointers. And the Boost library has others that are recommended. auto_ptr is depreciated in C++11, but the others are still there. Fall 2015CISC/CMPE320 - Prof. McLeod38

39 Smart Pointers, Cont. See: http://ootips.org/yonat/4dev/smart-pointers.html And: http://www.informit.com/articles/article.aspx?p=31529 Fall 2015CISC/CMPE320 - Prof. McLeod39


Download ppt "Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers."

Similar presentations


Ads by Google