Download presentation
Presentation is loading. Please wait.
1
CISC/CMPE320 - Prof. McLeod
Winter 2013 CISC/CMPE320 2/16/2019 CISC/CMPE320 Assignment 4 on using the heap is due today at 7pm. Presentation schedule was announced in last Friday’s lecture. No conflicts, yet. Is there any team that would like to switch on Tuesday the 27th from the lecture time to the tutorial time (and room)? Fall 2018 CISC/CMPE320 - Prof. McLeod Prof. Alan McLeod
2
CISC/CMPE320 - Prof. McLeod
Today Building templated classes and functions. The Standard Template Library or “STL”. Smart Pointers in C++. Fall 2018 CISC/CMPE320 - Prof. McLeod
3
CISC/CMPE320 - Prof. McLeod
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 strings? You don’t have a base Object type like you had in Java. The answer is to use a Template Function: Fall 2018 CISC/CMPE320 - Prof. McLeod
4
CISC/CMPE320 - Prof. McLeod
An Example, Cont. Prototype: template<typename T> void printArray(ostream&, const T[], int); When invoked, T can be any primitive type or object type. Fall 2018 CISC/CMPE320 - Prof. McLeod
5
CISC/CMPE320 - Prof. McLeod
An Example, Cont. Implementation: template<typename T> 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'; } Fall 2018 CISC/CMPE320 - Prof. McLeod
6
CISC/CMPE320 - Prof. McLeod
An Example, Cont. Note that you need the template<typename T> 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 <<). Fall 2018 CISC/CMPE320 - Prof. McLeod
7
CISC/CMPE320 - Prof. McLeod
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); Fall 2018 CISC/CMPE320 - Prof. McLeod
8
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. An alternative is to specify the type when you invoke the function: printArray<double>(cout, nums, 40); Fall 2018 CISC/CMPE320 - Prof. McLeod
9
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. Unlike Java generics, the C++ compiler cannot check this for you. Hint: build and debug the function with a concrete type first. Error messages that result from using Templates are harder to interpret. Fall 2018 CISC/CMPE320 - Prof. McLeod
10
Templates vs. Polymorphism
Templates supply a kind of compile-time polymorphism. Normal polymorphism is strictly a run-time process. A Templated Function is a function “factory”. Functions with the necessary types are created at compilation. As a result, the use of Templates has a very low run-time cost. Fall 2018 CISC/CMPE320 - Prof. McLeod
11
CISC/CMPE320 - Prof. McLeod
Specialization Occurs when you have an overloaded, non-templated version of the same templated function. If present, and the argument types match, then the non-template version will be used in preference to the template version. Fall 2018 CISC/CMPE320 - Prof. McLeod
12
CISC/CMPE320 - Prof. McLeod
Templated Classes Another example: Suppose you need a class to store a pair of anythings… Interface: template<typename F, typename S> class Pair { public: Pair(const F&, const S&); F getFirst() const; S getSecond() const; private: F first; S second; }; Fall 2018 CISC/CMPE320 - Prof. McLeod
13
CISC/CMPE320 - Prof. McLeod
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: Fall 2018 CISC/CMPE320 - Prof. McLeod
14
CISC/CMPE320 - Prof. McLeod
template<typename F, typename S> Pair<F, S>::Pair(const F& a, const S& b) : first(a), second(b) {} F Pair<F, S>::getFirst() const { return first; } S Pair<F, S>::getSecond() const { return second; Note how the template statement has to be repeated. Fall 2018 CISC/CMPE320 - Prof. McLeod
15
CISC/CMPE320 - Prof. McLeod
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: Fall 2018 CISC/CMPE320 - Prof. McLeod
16
CISC/CMPE320 - Prof. McLeod
Pair<double, double> 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<double, double>(low, high); Fall 2018 CISC/CMPE320 - Prof. McLeod
17
CISC/CMPE320 - Prof. McLeod
Reminder – typedef You might get tired of typing Pair<double, double> all the time! typedef Pair<double, double> PairDD; Simplifies findMinMax() a bit: Fall 2018 CISC/CMPE320 - Prof. McLeod
18
CISC/CMPE320 - Prof. McLeod
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); Fall 2018 CISC/CMPE320 - Prof. McLeod
19
CISC/CMPE320 - Prof. McLeod
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<typename T, int SIZE> When used, you would have to supply a type for T and an int for the second argument: AClass<double, 10> aVar; Fall 2018 CISC/CMPE320 - Prof. McLeod
20
CISC/CMPE320 - Prof. McLeod
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. Fall 2018 CISC/CMPE320 - Prof. McLeod
21
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. And, see links from: Fall 2018 CISC/CMPE320 - Prof. McLeod
22
Other Template Libraries
The Wikipedia entry under “List of C++ template libraries” provides links to the description of 34 library projects. Fall 2018 CISC/CMPE320 - Prof. McLeod
23
CISC/CMPE320 - Prof. McLeod
STL Classification STL components are classified in two different ways: By Category: Container Iterator Algorithm Function Object Utility Adaptor Allocator Fall 2018 CISC/CMPE320 - Prof. McLeod
24
STL Classification, Cont.
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. Fall 2018 CISC/CMPE320 - Prof. McLeod
25
CISC/CMPE320 - Prof. McLeod
STL #includes List The following lists are not complete and are missing some C++11 additions. Refer to better documentation such as that available from cplusplus.com Fall 2018 CISC/CMPE320 - Prof. McLeod
26
STL #includes - Containers
<vector> vector <list> doubly linked list <deque> doubly ended queue <queue> queue <stack> stack <map> associative arrays – multimap <set> set – multiset <bitset> array of booleans Fall 2018 CISC/CMPE320 - Prof. McLeod
27
STL #includes – General Utilities
<utility> operators and pairs <functional> function objects <memory> allocators for containers <ctime> C-style date and time Fall 2018 CISC/CMPE320 - Prof. McLeod
28
STL #includes – Iterators
<iterator> iterators and iterator support Fall 2018 CISC/CMPE320 - Prof. McLeod
29
STL #includes – Algorithms
<algorithm> general algorithms <cstdlib> bsearch(), qsort() Fall 2018 CISC/CMPE320 - Prof. McLeod
30
STL #includes – Diagnostics
<exception> exception classes <stdexcept> standard exceptions <cassert> assert macro <cerrno> C-style error handling Fall 2018 CISC/CMPE320 - Prof. McLeod
31
STL #includes – Strings
<string> string <cctype> character classification <cwctype> wide character classification <cstring> C-style string functions <cwchar> C-style wide character string functions <cstdlib> C-style string functions (<cstring> has strlen(), strcpy(), etc.; <cstdlib> has atof() and atoi() for string to number conversion.) Fall 2018 CISC/CMPE320 - Prof. McLeod
32
STL #includes – Input/Output
<iosfwd> forward declaration of I/O facilities <iostream> standard iostream stuff <ios> iostream bases <streambuf> stream buffers <istream> input stream template <ostream> output stream template <iomanip> manipulators <sstream> string streams <fstream> file streams <cstdio> printf() I/O stuff <cwchar> printf() for wide characters Fall 2018 CISC/CMPE320 - Prof. McLeod
33
STL #includes – Localization
<locale> represent cultural differences <clocale> C-style cultural differences Fall 2018 CISC/CMPE320 - Prof. McLeod
34
STL #includes – Language Support
<limits> numeric limits <climits> C-style numeric limit macros <cfloat> C-style floating point limit macros <new> dynamic memory management <typeinfo> run-time object identification <exception> exception handling <cstddef> C library language support <cstdarg> variable length function argument lists <csetjmp> C-style stack unwinding <cstdlib> program termination <ctime> system clock <csignal> C-style signal handling Fall 2018 CISC/CMPE320 - Prof. McLeod
35
STL #includes – Numerics
<complex> complex numbers and operations <valarray> numeric vectors and operations <numeric> general numeric operations <cmath> standard mathematical functions <cstdlib> C-style random numbers Fall 2018 CISC/CMPE320 - Prof. McLeod
36
STL #includes – Threading
<atomic> synchronized atomic types <thread> creates threads <mutex> locking of threads <condition_variable> blocking variables <future> provides asynchronous access All these are only in C++11 and came from the Boost library originally Fall 2018 CISC/CMPE320 - Prof. McLeod
37
CISC/CMPE320 - Prof. McLeod
Smart Pointers Follow the “proxy pattern” In the STL and in Boost. For example, see unique_ptr in <memory> (auto_ptr is depreciated.) 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 2018 CISC/CMPE320 - Prof. McLeod
38
CISC/CMPE320 - Prof. McLeod
Smart Pointers, Cont. Another answer is to wrap a pointer in another type that controls the behaviour of the pointer: template <class T> 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 2018 CISC/CMPE320 - Prof. McLeod
39
CISC/CMPE320 - Prof. McLeod
Smart Pointers, Cont. So, instead of writing: void foo() { MyClass* p = new MyClass; p->DoSomething(); delete p; } Fall 2018 CISC/CMPE320 - Prof. McLeod
40
CISC/CMPE320 - Prof. McLeod
Smart Pointers, Cont. You write: void foo() { auto_ptr<MyClass> 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 2018 CISC/CMPE320 - Prof. McLeod
41
CISC/CMPE320 - Prof. McLeod
Smart Pointers, Cont. C++11 smart pointers implement automatic garbage collection. You can avoid many common memory problems and make pointers easier to use. The STL has several implementations of smart pointers. And the Boost library has others that are recommended. unique_ptr is good for all-round use. Fall 2018 CISC/CMPE320 - Prof. McLeod
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.