Generic programming Define software components with type parameters –A sorting algorithm has the same structure, regardless of the types being sorted –Stack.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
1111 Abstract Data Types Cpt S 223. School of EECS, WSU.
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Modules Program is built out of components. Each component defines a set of logically related entities (strong internal coupling) A component has a public.
CHAPTER 7 Queues.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Generic programming Define software components with type parameters –A sorting algorithm has the same structure, regardless of the types being sorted –Stack.
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,
Modules Program is built out of components. Each component defines a set of logically related entities (strong internal coupling) A component has a public.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
1 Generic Programming. 2 Why? Sometimes a datum is just a datum Sometimes a datum is just a datum Operate on unrelated data types Operate on unrelated.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Generic programming Define software components with type parameters –A sorting algorithm has the same structure, regardless of the types being sorted –Stack.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation - FIFO As items are added they are chronologically ordered, items are removed.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Templates and the STL.
Templates Zhen Jiang West Chester University
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Containers Overview and Class Vector
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
Object Oriented Programming Elhanan Borenstein Lecture #11 copyrights © Elhanan Borenstein.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Porting Implementation of Packet Utilization Standard from ADA to JAVA Annelie Hultman (TEC-EME) Donata Pedrazzani (TEC-EMS) ESA/ESTEC 2004 JPUS de-briefing.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
(1) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
114 3/30/98 CSE 143 Collection ADTs [Chapter 4] /30/98 Collection ADTs  Many standard ADTs are for collections  Data structures that manage groups.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Queues 1. Introduction A sequential collection of data Changes occur at both ends, not just one Queue applications –files waiting to be printed –"jobs"
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
CPSC 252 Templatization Page 1 Templatization In CPSC152, we saw a class vector in which we could specify the type of values that are stored: vector intData(
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Records type city is record -- Ada Name: String (1..10); Country : String (1..20); Population: integer; Capital : Boolean; end record; struct city { --
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Abstract Data Types Queues Dale Roberts, Lecturer
CS505 Data Structures and Algorithms
UNIT-3 LINKED LIST.
CSE 143 Linked Lists [Chapter , 8.8] 3/30/98.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
[Chapter 4; Chapter 6, pp ] CSC 143 Linked Lists [Chapter 4; Chapter 6, pp ]
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Containers: Queue and List
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 Abstraction - The concept of abstraction is fundamental in
Presentation transcript:

Generic programming Define software components with type parameters –A sorting algorithm has the same structure, regardless of the types being sorted –Stack primitives have the same semantics, regardless of the –objects stored on the stack. Most common use: algorithms on containers: updating, iteration, search C model: macros (textual substitution) Ada model: generic units and instantiations C++ model: templates

Parametrizing software components Construct parameter supplying parameter array values (bounds) declaring object declaring subtype record discriminant object/subtype subprogram values (actuals) calling subprogram generic unit types, values instantiating template classes, values instantiating, specializing

Generics in Ada95 I/O for integer types. Identical implementation, but need separate procedures for strong-typing reasons. generic type Elem is range <> ; -- any integer type package Integer_IO is procedure Put (Item : Elem);...

generic type Elem is private; -- parameter package Stacks is type Stack is private; procedure Push (X : Elem; On : in out Stack); … private type Cell; type Stack is access Cell; -- linked list representation type Cell is record Val : Elem; Next : Ptr; end record; end Stacks; A generic Package

Instantiations with Stacks; procedure Test_Stacks is package Int_Stack is new Stacks (Integer); -- list of integers package Float_Stack is new Stacks (Float); -- list of floats S1 : Int_Stack.Stack; -- a stack object S2 : Float_Stack.Stack; use Int_Stack, Float_Stack; -- ok, regular packages begin Push (15, S1); -- Int_Stack.Push Push (3.5 * Pi, S2);... end Test_Stacks;

Type parameters The generic type declaration specifies the class of types for which an instance of the generic will work: type T is private; -- any type with assignment (Non-limited) type T is limited private; -- any type (no required operations) type T is range <>; -- any integer type (arithmetic operations) type T is (<>); -- any discrete type (enumeration or -- integer) type T is digits <>; -- any floating-point type type T is delta <>; -- any fixed-point type Within the generic, the operations that apply to any type of the class can be used. The instantiation must use a specific type of the class

A generic function generic type T is range <>; -- parameter of some integer type type Arr is array (Integer range <>) of T; -- parameter is array of those function Sum_Array (A : Arr) return T; -- Body identical to non-generic version function Sum_array (A : Arr) return T is Result : T := 0; -- some integer type, so literal 0 is legal begin for J in A’range loop -- some array type, so attribute is available Result := Result + A (J); -- some integer type, so “+” available. end loop; return Result; end;

Instantiating a generic function type Apple is range **15 - 1; type Production is array (1..12) of Apple; type Sick_Days is range 1..5; type Absences is array (1.. 52) of Sick_Days; function Get_Crop is new Sum_array (Apple, Production); function Lost_Work is new Sum_array (Sick_Days, Absences);

generic private types Only available operations are assignment and equality. generic type T is private; procedure Swap (X, Y : in out T); procedure Swap (X, Y : in out T) is Temp : constant T := X; begin X := Y; Y := Temp; end Swap;

Subprogram parameters A generic sorting routine should apply to any array whose components are comparable, i.e. for which an ordering predicate exists. This class includes more that the numeric types: generic type T is private; -- parameter with function “<“ (X, Y : T) return Boolean; -- parameter type Arr is array (Integer range <>) of T; -- parameter procedure Sort (A : in out Arr);

Supplying subprogram parameters The actual must have a matching signature, not necessarily the same name: procedure Sort_Up is new Sort (Integer, “<“, …); procedure Sort_Down is new Sort (Integer, “>”, … ); type Employee is record.. end record; function Senior (E1, E2 : Employee) return Boolean; procedure Rank is new Sort (Employee, Senior, …);

Value parameters Useful to parametrize containers by size: generic type Elem is private; -- type parameter Size : Positive; -- value parameter package Queues is type Queue is private; procedure Enqueue (X : Elem; On : in out Queue); procedure Dequeue (X : out Elem; From : in out Queue); function Full (Q : Queue) return Boolean; function Empty (Q : Queue) return Boolean; private type Contents is array (Natural range <>) of Elem; type Queue is record Front, Back: Natural; C : Contents (0.. Size); end record; end Queues;

Packages as parameters If interface includes a type and its operations, the parameter can be a single generic package: generic type Real is digits <>; -- any floating type package generic_complex_types is -- complex is a record with two real components -- package declares all complex operations: +, -, Re, Im... end generic_complex_types; We also want to define a package for elementary functions (sin, cos, etc.) on complex numbers. We need the complex operations, which are parametrized by the corresponding real value.

The instantiation requires an instance of the parameter with generic_complex_types; generic with package compl is new generic_complex_types (<>); package generic_complex_elementary_functions is -- trigonometric, exponential, hyperbolic functions. end generic_complex_elementary_functions; Instantiate complex types with long_float components: package long_complex is new generic_complex_type (long_float); Instantiate complex functions for long_complex types: package long_complex_functions is new generic_complex_elementary_functions (long_complex);

Templates in C++ template class Vector { public: Vector (size_t n); -- constructor T& operator [ ] (size_t); -- subscript (hopefully with checks!) private: … // a struct with a size and a pointer to an array }; Vector V1 (100); -- instantiation Vector Vdef; -- use default constructor typedef Vector Dept; -- named instance

Class and value parameters template class Buffer { T v [i]; -- storage for buffer int sz; -- total capacity int count; -- current contents public: Buffer( ) : sz (i), count (0) { }; T read (); void write (T elem); }; Buffer picture; -- instance for a graphics app.

Template hopes for the best template class List { struct Link { // for a list node Link* pre; // doubly linked Link* succ; T val; Link (Link* p, s, const T& v): pre (p), succ(s), val (v) { }; } Link * head; public: void print_all () { for Link*p = head; p; p=p->succ) cout val << ‘\n’; // operator<< better exist for T! };

Function templates Instantiated implicitly at point of call. template void sort (vector &) {..}; void testit ( &vi) { sort (vi); // can also write sort (vi); };

Functions and function templates Templates and regular functions overload each other: template class complex {…}; template T sqrt (T); // template template complex sqrt (complex ); // different algorithm double sqrt (double); // regular function void testit (complex cd) { sqrt (2); // sqrt : specialization of template sqrt (2.0); // sqrt (double): regular function sqrt (cd); // sqrt( (complex ): specialization };

Iterators and containers Containers are standard data structures to manage collections –insert, delete, search, count Standard algorithms over collections use iterators: template class Iterator { Iterator (Coll over) {..}; // build iterator for given collection Elem* First_Elem ( ); // start iteration Elem* Next_Elem ( ); // move to next element in collection bool done (); // termination condition };