Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Similar documents
Class and Function Templates

Motivation for Templates

Assignment of Objects

CS201 - Introduction to Programming Glossary By

CS 2604 Homework 1 C++ Review Summer I 2003

CS 2604 Homework 1 Greatest Hits of C++ Summer 2000

Short Notes of CS201

CS 2604 Homework 2 Solution for Greatest Hits of C++ Fall 2000

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Lab 2: ADT Design & Implementation

COEN244: Class & function templates

Logistics. Templates. Plan for today. Logistics. A quick intro to Templates. A quick intro to Templates. Project. Questions? Introduction to Templates

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Function Overloading

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Link-Based Implementations. Chapter 4

Definition of Stack. 5 Linked Structures. Stack ADT Operations. ADT Stack Operations. A stack is a LIFO last in, first out structure.

ADT Sorted List Operations

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

CSCE 110 PROGRAMMING FUNDAMENTALS

GEA 2017, Week 4. February 21, 2017

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

CSCE 110 PROGRAMMING FUNDAMENTALS

CS302 Data Structures using C++

CS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren

Instantiation of Template class

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

This examination has 11 pages. Check that you have a complete paper.

CS 1704 Intro Data Structures and Software Engineering Test 2 Fall 2001 READ THIS NOW!

การทดลองท 8_2 Editor Buffer Array Implementation

EECE.3220: Data Structures Spring 2017

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Introducing C++ to Java Programmers

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Introduction to C++ Systems Programming

Intermediate Programming, Spring 2017*

Lecture 7. Log into Linux New documents posted to course webpage

CS302 - Data Structures using C++

Object Oriented Design

Chapter 9 Classes : A Deeper Look, Part 1

Due Date: See Blackboard

Scope. Scope is such an important thing that we ll review what we know about scope now:

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

! A data type for which: ! An ADT may be implemented using various. ! Examples:

pointers & references

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Linked List using a Sentinel

CMSC 341 Lecture 7 Lists

CS427 Inheritance and Virtual Functions. Linked lists. 2/27. 01Replacement.cpp link! i n t GetY ( void ) { return ( y ) ; } ;

Propedéutico de Programación

C++ Basics. Rationale for the C++ Class. Rationale for the C++ Class. Encapsulation and Information Hiding. Interface for a Simple Date Class

CSCI 123 Introduction to Programming Concepts in C++

CPSC 427: Object-Oriented Programming

Dynamic Data Structures

Chapter 18: Stacks And Queues

Object-Oriented Principles and Practice / C++

Chapter 18: Stacks And Queues

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

ADT Unsorted List. Outline

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

C++ Object-Oriented Programming

Financial computing with C++

Chapter 18: Stacks And Queues. Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Object-Oriented Programming

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Faculty of Information and Communication Technologies

ADTs: Stacks and Queues

Data Structures and Algorithms

Intermediate Programming & Design (C++) Classes in C++

Implementing an ADT with a Class

III. Classes (Chap. 3)

Chapter 12 - Templates

CPSC 427: Object-Oriented Programming

CSC1322 Object-Oriented Programming Concepts

Practice Problems CS2620 Advanced Programming, Spring 2003

COMP 2355 Introduction to Systems Programming

1 Short Answer (7 Points Each)

CS24 Week 3 Lecture 1

COMP322 - Introduction to C++ Lecture 07 - Introduction to C++ classes

explicit class and default definitions revision of SC22/WG21/N1582 =

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

And Even More and More C++ Fundamentals of Computer Science

CS212 - COMPUTATIONAL STRUCTURES AND ALGORITHMS

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Doubly-Linked Lists

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

ADT: Design & Implementation

An Introduction to Queues With Examples in C++

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID#

ComS 228 Exam 1. September 27, 2004

ADTs in C++ In C++, member functions can be defined as part of a struct

Object-Oriented Principles and Practice / C++

SFU CMPT Topic: Class Templates

eingebetteter Systeme

Transcription:

Class and Function 1 Motivation for 2 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing Template Class Methods A Complete Template Queue Class A Driver for the QueueT Template Recap Implicit Assumptions in QueueT Variable and Constant Template Parameters Queue Template with a Variable Parameter Driver for Revised Queue Template Template Type-checking Linked List Template Linked List Node Template A Node Template Constructor Node Template Mutators Node Template Reporters Linked List Template Destructor Linked List Template Prefix Function Linked List Template Assignment Overload Linked List Template Copy Constructor Template Functions Template Sort Function You want both: a list of Location objects a list of MazeMonster objects How can you accomplish this by writing one LinkedList class? state all the ways you can think of doing this state the pros/cons of each method One Way to Look at... 3 Example: Queue of some type Foo 4 Until now, we have used variables: The type of a variable is fixed when you write code. The value of a variable isn t fixed when you write code. With templates, type isn t fixed when you write code! With templates, you use a type more or less as a variable! template <class Foo> class Queue { Parameter, can be any type C++ keywords Foo buffer[100]; int head, tail, count; Queue(); void Insert(Foo item); Foo Remove(); ~Queue(); ; The header of a templated class declaration specifies one or more type names which are then used within the template declaration. These type names are typically NOT standard or user-defined types, but merely placeholder names that serve as formal parameters. 1

C++ Definition of template : Parameterized class with parameters that denote unknown types. Usage: In situations where the same algorithms and/or data structures need to be applied to different data types. Declaration syntax: template <class Foo> class Queue { template member declarations go here ; 5 What can a parameter be used for? To specify the type specifying of data which will be local to objects of the class: Foo buffer[100]; To specify the type of a parameter to a class member function: void Insert(Foo item); To specify the return type of a class member function: 6 Foo Remove(); Instantiating a Template 7 Usage of 8 Given the template declaration: template <class Foo> class Queue {...; Instantiate Queue of ints in 2 ways: Queue<Location> intqueue; typedef Queue<int> IntegerQueue; IntegerQueue intqueue; Both of these define an object intqueue. Once created, the template object is used like any other object: intqueue.insert(100); add 100 to the queue intqueue.insert(200); add 200 The parameter type for the member function Insert() was specified as Foo in the template declaration and mapped to int in the declaration of the object intqueue. When calling Insert() we supply an int value. Note how an actual type (Location or int) is substituted for the template parameter (Foo) in the object declaration. int x = intqueue.remove(); remove 100 intqueue.insert(300); queue now has (200,300) int Sz = intqueue.size(); size is 2 2

Compiler view of templates... 9 Implementing Template Class Methods 10 The compiler macro expands the template code: You write Queue<int> intqueue. Compiler emits new copy of a class named Queueint and substitutes <int> for <Foo> throughout. Therefore, the compiler must have access to the implementation of the template member functions in order to carry out the substitution. Therefore, the template implementation CANNOT be pre-compiled. Most commonly, all template code goes in the header file with the template declaration. The compiler maps the declaration: Foo buffer[100]; to the declaration: The compiler mangles the template name with the actual parameter (type name) to produce a unique name for the class. Queueint buffer[100]; template and actual parameter(s) Class name and actual parameter(s) template<class Foo> Queue<Foo>::Queue() {... member function body goes here Return type goes here: Scope resolution operator and function name template<class Foo> void Queue<Foo>::Insert(Foo item) {... member function body goes here A Complete Template Queue Class 11 A Complete Template Class 12 QueueT.h #ifndef QUEUET_H #define QUEUET_H #include <cassert> const int Size = 100; template <class Foo> class QueueT { Foo buffer[size]; int Head, Tail, Count; QueueT(); void Enqueue(Foo Item); Foo Dequeue(); int getsize() const; bool isempty() const; bool isfull() const; ~QueueT(); ;... template implementation goes here #endif Using the template parameter: data type, parameter type, return type.... continuing header file QueueT.h template <class Foo> QueueT<Foo>::QueueT() : Head(0), Tail(0), Count(0) { template <class Foo> void QueueT<Foo>::Enqueue(Foo Item) { assert(count < Size); die if Queue is full! buffer[tail] = Item; Tail = (Tail + 1) % Size; circular array indexing Count++; 3

A Complete Template Class 13 A Complete Template Class 14... continuing header file QueueT.h... continuing header file QueueT.h template <class Foo> Foo QueueT<Foo>::Dequeue() { template <class Foo> bool QueueT<Foo>::isEmpty() const { assert(count > 0); die if Queue is empty int oldhead = Head; remember where old Head was Head = (Head + 1) % Size; reset Head Count--; return buffer[oldhead]; return old Head return (Count == 0); template <class Foo> bool QueueT<Foo>::isFull() const { return (Count < Size - 1); template <class Foo> int QueueT<Foo>::getSize() const { return (Count); template <class Foo> QueueT<Foo>::~QueueT() {... end template QueueT<Foo> implementation A Driver for the QueueT Template 15 Recap 16 #include <iostream> #include <iomanip> using namespace std; #include "QueueT.h" void main() { const int numvals = 10; QueueT<int> intq; for (int i = 0; i < numvals; i++) { intq.enqueue(i*i); 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 int Limit = intq.getsize(); for (i = 0; i < Limit; i++) { int nextval = intq.dequeue(); cout << setw(3) << i << setw(5) << nextval << endl; Note that method bodies use the same algorithms for a queue of ints or a queue of doubles or a queue of Locations But the compiler still type checks! It does a macro expansion, so if you declare QueueT<int> iqueue; QueueT<char> cqueue; QueueT<Location> Vertices; the compiler has three different classes after expansion to use with normal type checking rules. 4

Implicit Assumptions in QueueT 17 Implicit Assumptions in QueueT 18 Declaration of the array of Foos assumes Foo has a default constructor: template <class Foo> class Queue { Foo buffer[size];... ; The way that Foos are returned by Remove() method assumes Foo has provided an appropriate copy constructor: template <class Foo> Foo Queue<Foo>::Remove() {... return buffer[val]; Assignment of Foos assumes Foo has appropriately overloaded the assignment operator: template <class Foo> void Queue<Foo> ::Insert(Foo item) {... buffer[tail] = item;... ; Variable and Constant Template Parameters 19 Queue Template with a Variable Parameter 20 Template parameters may be: type names variables constants (we saw this previously) e.g., to specify a size for a data structure useful to define templates for special cases (not terribly useful) One weakness of the QueueT template is that the queue array is of a fixed size. We can easily make that user-selectable: template <class Foo, int Size> class QueueT { Foo buffer[size]; int Head, Tail; Second template parameter is int Count; just an int variable, which falls within the class scope QueueT(); just as a private data member bool Enqueue(Foo Item); would. bool Dequeue(Foo& Item); int getsize() const; bool isempty() const; bool isfull() const; ~QueueT(); ; 5

Driver for Revised Queue Template 21 Template Type-checking 22 #include <iostream> #include <iomanip> using namespace std; #include "QueueT.h" void main() { const int smallsize = 10; const int largesize = 100; QueueT<int, smallsize> smallq; QueueT<int, largesize> largeq; for (int i = 0; i < smallsize-1; i++) smallq.enqueue(i); for (i = 0; i < largesize-1; i++) { largeq.enqueue(i); The value specified in the declaration must still be a constant though that could be avoided by redesigning the template to take the array size as a parameter to a constructor Suppose we have the declarations: QueueT<int, 100> smallintegerqueue; QueueT<int, 1000> largeintegerqueue; QueueT<int, 1000> largeintegerqueue2; QueueT<float, 100> smallrealqueue; QueueT<float, 1000> largerealqueue; Which (if any) of the following are legal assignments: smallintegerqueue = largeintegerqueue; for (i = 0; i < smallsize-1; i++) { int nextval; largeq.dequeue(nextval); cout << setw(3) << i << setw(5) << nextval << endl; smallintegetqueue = smallrealqueue; largeintegerqueue = largeintegerqueue2; Linked List Template 23 Linked List Template 24 LinkListT.h #ifndef LINKLISTT_H #define LINKLISTT_H #include <cassert> #include "LinkNodeT.h" class LinkListT { LinkNodeT<ItemType>* Head; points to head node in list LinkNodeT<ItemType>* Tail; points to tail node in list LinkNodeT<ItemType>* Curr; points to "current" node in list These are pointers to template objects so any template parameters must be specified explicitly. LinkListT(); LinkListT(const LinkListT<ItemType>& Source); ~LinkListT(); Function parameter is a template object, so...... bool isempty() const; bool morelist() const; bool PrefixNode(ItemType newdata); bool AppendNode(ItemType newdata); bool InsertAfterCurr(ItemType newdata); bool Advance(); void gotohead(); void gototail(); bool MakeEmpty(); bool DeleteCurrentNode(); bool DeleteValue(ItemType Target); ItemType getcurrentdata() const; void PrintList(ostream& Out); LinkListT<ItemType>& operator=(const LinkListT<ItemType>& Source); ; Operator return type is a template object, so #include "LinkListT.cpp" #endif 6

Linked List Node Template 25 A Node Template Constructor 26 LinkNodeT.h #ifndef LINKNODET_H #define LINKNODET_H class LinkNodeT { ItemType Data; LinkNodeT<ItemType>* Next; LinkNodeT(); LinkNodeT(ItemType newdata); void setdata(itemtype newdata); void setnext(linknodet<itemtype>* newnext); ItemType getdata() const; LinkNodeT<ItemType>* getnext() const; ; Function return type is a template object, so #include "LinkNodeT.cpp" Constructor for LinkNode objects with assigned Data field. Parameters: newdata Data element to be stored in node Pre: none Post: new LinkNode has been created with given Data field and NULL pointer LinkNodeT<ItemType>::LinkNodeT(ItemType newdata) { Data = newdata; Next = NULL; #endif Node Template Mutators 27 Node Template Reporters 28 Sets new value for Data element of object. Parameters: newdata Data element to be stored in node Pre: none Post: Data field of object has been modified to hold newdata void LinkNodeT<ItemType>::setData(ItemType newdata) { Data = newdata; Suppressed to save space. void LinkNodeT<ItemType>::setNext(LinkNodeT<ItemType>* newnext) { Next = newnext; Returns value of Data element of object. Parameters: none Pre: object has been initialized Post: Data field of object has been returned ItemType LinkNodeT<ItemType>::getData() const { return Data; Suppressed to save space. LinkNodeT<ItemType>* LinkNodeT<ItemType>::getNext() const { return Next; 7

Linked List Template Destructor 29 Linked List Template Prefix Function 30 Destructor for LinkListT objects. Parameters: none Pre: LinkListT object has been constructed Post: LinkListT object has been destructed; all dynamically-allocated nodes have been deallocated. LinkListT<ItemType>::~LinkListT() { Inserts a new LinkNodeT at the front of the list. bool LinkListT<ItemType>::PrefixNode(ItemType newdata) { LinkNodeT<ItemType>* newnode = new LinkNodeT<ItemType>(newData); if (newnode == NULL) return false; LinkNodeT<ItemType>* tokill = Head; while ( tokill!= NULL) { Head = Head->getNext(); delete tokill; tokill = Head; if ( isempty() ) { newnode->setnext(null); Head = Tail = Curr = newnode; return true; newnode->setnext(head); Head = newnode; return true; Linked List Template Assignment Overload 31 Linked List Template Copy Constructor 32 / Deep copy assignment operator for LinkListT objects. LinkListT<ItemType>& LinkListT<ItemType>:: operator=(const LinkListT<ItemType>& Source) { if (this!= &Source) { MakeEmpty(); delete target's list, if any LinkNodeT<ItemType>* mycurr = Source.Head; copy list while (mycurr!= NULL) { ItemType xferdata = mycurr->getdata(); AppendNode(xferData); mycurr = mycurr->getnext(); return *this; / Deep copy constructor for LinkListT objects. LinkListT<ItemType>::LinkListT(const LinkListT<ItemType>& Source) { Head = Tail = Curr = NULL; LinkNodeT<ItemType>* mycurr = Source.Head; while (mycurr!= NULL) { ItemType xferdata = mycurr->getdata(); AppendNode(xferData); mycurr = mycurr->getnext(); copy list 8

Template Functions 33 Template Sort Function 34 The template mechanism may also be used with non-member functions: template <class Foo> Swap(Foo& First, Foo& Second) { Foo tmpfoo = First; First = Second; Second = tmpfoo; Given the template function above, we may swap the value of two variables of ANY type, provided that a correct assignment operation and copy constructor are available. However, the two actual parameters MUST be of exactly the same type: double X = 3.14159; int a = 5; Swap(a, X); error at compile time template <class Foo> InsertionSort(Foo* const A, int Size) { int Begin, Look; Foo Item; for (Begin = 1; Begin < Size; Begin++) { Look = Begin - 1; Item = A[Begin]; while ( Look >= 0 && A[Look] > Item) { A[Look + 1] = A[Look]; Look--; A[Look + 1] = Item; This will use the insertion sort algorithm to sort an array holding ANY type of data, provided that there are > and deep = operators for that type (if a deep assignment is logically necessary). 9