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

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms The C Programming Language.
Advertisements

Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Review of C++ Programming Part II Sheng-Fang Huang.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Java and C++, The Difference An introduction Unit - 00.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
By – Tanvir Alam.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google. 
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers OVERVIEW.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Arrays and Vectors Sequential (One-Dimensional) Containers Chapter 12 1.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Overview of C++ Templates
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Problems with assn 3? Discuss at your team meeting tonight.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). SDD document framework should be set up in your Wiki by now.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Scuola Superiore Sant’Anna Advanced Course on C++ IV Giuseppe Lipari.
C++ Templates.
Introduction to C++ Systems Programming.
Exceptions, Templates, and the Standard Template Library (STL)
C Basics.
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
Standard Version of Starting Out with C++, 4th Edition
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
Exceptions, Templates, and the Standard Template Library (STL)
Java Programming Language
SPL – PS1 Introduction to C++.
Presentation transcript:

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

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:

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.

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'; }

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 <<).

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);

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);

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.

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.

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.

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; };

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:

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.

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:

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); }

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:

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); }

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;

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.

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”: And links from:

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

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

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.

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

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

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

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

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

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.)

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

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

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

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

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

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

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

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

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

Smart Pointers, Cont. See: And: Fall 2015CISC/CMPE320 - Prof. McLeod39