+ All Categories
Home > Documents > 1 Generic Programming. 2 Why? Sometimes a datum is just a datum Sometimes a datum is just a datum...

1 Generic Programming. 2 Why? Sometimes a datum is just a datum Sometimes a datum is just a datum...

Date post: 20-Dec-2015
Category:
View: 221 times
Download: 1 times
Share this document with a friend
Popular Tags:
35
1 Generic Generic Programming Programming
Transcript
Page 1: 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.

11

Generic Generic ProgrammingProgramming

Page 2: 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.

22

Why?Why? Sometimes a datum is just a datumSometimes a datum is just a datum Operate on unrelated data typesOperate on unrelated data types

Container classesContainer classes Equality operatorEquality operator Swap methodSwap method Sorting proceduresSorting procedures

Code reuseCode reuse Build programs from small reusable generic Build programs from small reusable generic

partsparts Avoid copying or reinventing the same codeAvoid copying or reinventing the same code

Page 3: 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.

33

Generic ProgrammingGeneric Programming

Compile time parametersCompile time parameters ImplementationImplementation

Same codeSame code used for different parameter values used for different parameter values Different codeDifferent code generated for different values generated for different values

Generic programming in ML Generic programming in ML Generics in ADAGenerics in ADA Java 1.5 – GJ & PizzaJava 1.5 – GJ & Pizza C++ Standard Template LibraryC++ Standard Template Library Containers and IteratorsContainers and Iterators

Page 4: 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.

44

Generic programmingGeneric programming

Define software components with type parametersDefine software components with type parameters A sorting algorithm has the same structure, regardless of A sorting algorithm has the same structure, regardless of

the types being sortedthe types being sorted Stack primitives have the same semantics, regardless of Stack primitives have the same semantics, regardless of

thethe objects stored on the stack.objects stored on the stack.

Most common use: algorithms on Most common use: algorithms on containerscontainers: : updating, iteration, searchupdating, iteration, search

C modelC model: macros (textual substitution): macros (textual substitution) Ada modelAda model: generic units and instantiations: generic units and instantiations C++ modelC++ model: templates: templates ML and Java 1.5: type inferenceML and Java 1.5: type inference

Page 5: 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.

55

Parameterizing Software Parameterizing Software ComponentsComponents

Construct Construct ParameterParameter Supplying parameterSupplying parameter array values (bounds) declaring objectarray values (bounds) declaring object declaring subtypedeclaring subtype record discriminant object/subtyperecord discriminant object/subtype subprogram values (actuals) calling subprogramsubprogram values (actuals) calling subprogram generic unit types, values generic unit types, values instantiatinginstantiating template classes, values template classes, values instantiatinginstantiating,, specializingspecializing

Page 6: 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.

66

Generics in Ada95Generics in Ada95

• I/O for integer types. Identical implementation, I/O for integer types. Identical implementation, but need separate procedures for strong-typing but need separate procedures for strong-typing reasons.reasons.

genericgeneric typetype Elem Elem is rangeis range <> ; <> ; -- any integer type-- any integer type packagepackage Integer_IO is Integer_IO is procedureprocedure Put (Item : Elem); Put (Item : Elem); ......

Page 7: 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.

77

genericgeneric typetype Elem Elem is privateis private;; -- compile time -- compile time

parameterparameter packagepackage Stacks Stacks isis typetype Stack Stack is privateis private;; procedureprocedure Push (X : Elem; On : Push (X : Elem; On : in outin out Stack); Stack); … … privateprivate typetype Cell; Cell; typetype Stack Stack is accessis access Cell; Cell; -- linked list -- linked list

representationrepresentation typetype Cell Cell is recordis record Val : Elem;Val : Elem; Next : Ptr;Next : Ptr; end recordend record;; endend Stacks; Stacks;

A generic PackageA generic Package

Page 8: 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.

88

InstantiationsInstantiations withwith Stacks; Stacks; procedureprocedure Test_Stacks Test_Stacks isis packagepackage Int_Stack Int_Stack is newis new Stacks (Integer); Stacks (Integer); -- Package for -- Package for

integersintegers packagepackage Float_Stack Float_Stack is newis new Stacks (Float); Stacks (Float); -- Package for -- Package for

floatsfloats S1 : Int_Stack.Stack; S1 : Int_Stack.Stack; -- an integer stack object-- an integer stack object S2 : Float_Stack.Stack;S2 : Float_Stack.Stack; -- a float stack object-- a float stack object use Int_Stack, Float_Stack; use Int_Stack, Float_Stack; -- ok, regular packages-- ok, regular packages beginbegin Push (15, S1); Push (15, S1); -- Int_Stack.Push-- Int_Stack.Push Push (3.5 * Pi, S2);Push (3.5 * Pi, S2); ...... endend Test_Stacks; Test_Stacks;

Page 9: 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.

99

Type parametersType parameters

The generic type declaration specifies the The generic type declaration specifies the classclass of of types for which an instance of the generic will work:types for which an instance of the generic will work:

• type type TT is private; is private; -- any type with assignment (Non--- any type with assignment (Non-limited)limited)

• type type TT is limited private; is limited private; -- any type (no required operations)-- any type (no required operations)• type type TT is range <>; is range <>; -- any integer type (arithmetic -- any integer type (arithmetic

operations)operations)• type type TT is (<>); is (<>); -- any discrete type (enumeration or-- any discrete type (enumeration or

• -- integer)-- integer)• type type TT is digits <>; is digits <>; -- any floating-point type-- any floating-point type• type type TT is delta <>; is delta <>; -- any fixed-point type-- any fixed-point type

• Within the generic, the operations that apply to any type of the Within the generic, the operations that apply to any type of the class can be used.class can be used.

• The instantiation must use a specific type of the classThe instantiation must use a specific type of the class

Page 10: 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.

1010

A generic functionA generic function

genericgeneric type type TT is range <>; is range <>; -- parameter of some integer -- parameter of some integer

typetype typetype ArrArr is arrayis array ( (IntegerInteger range <>) ofrange <>) of T; T; -- parameter is array of those-- parameter is array of those functionfunction Sum_Array (A : Arr)Sum_Array (A : Arr) returnreturn T;T;

-- Body identical to non-generic version-- Body identical to non-generic version functionfunction Sum_array (A : Arr)Sum_array (A : Arr) returnreturn TT isis Result : T := 0; Result : T := 0; -- some integer type, so literal 0 is -- some integer type, so literal 0 is

legallegal beginbegin forfor JJ inin A’rangeA’range looploop -- some array type, so attribute is -- some array type, so attribute is

availableavailable Result := Result + A (J); Result := Result + A (J); -- some integer type, so “+” available.-- some integer type, so “+” available. end loop;end loop; returnreturn ResultResult;; end;end;

Page 11: 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.

1111

Instantiating a generic functionInstantiating a generic function

-- Define types for Apple Production-- Define types for Apple Production typetype Apple Apple is rangeis range 1 .. 2 **15 - 1;1 .. 2 **15 - 1; typetype ProductionProduction is arrayis array (1..12)(1..12) ofof Apple;Apple; -- Define types for Sick Days-- Define types for Sick Days typetype Sick_DaysSick_Days is rangeis range 1..5;1..5; typetype AbsencesAbsences is arrayis array (1 .. 52)(1 .. 52) ofof Sick_Days; Sick_Days;

-- Instantiate definite functions from the generic-- Instantiate definite functions from the generic functionfunction Get_Crop Get_Crop is newis new Sum_array (Apple, Production); Sum_array (Apple, Production); functionfunction Lost_Work Lost_Work is newis new Sum_array (Sick_Days, Absences); Sum_array (Sick_Days, Absences);

Page 12: 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.

1212

Generic private typesGeneric private types

• Only available operations are assignment and Only available operations are assignment and

equalityequality.. genericgeneric typetype TT is privateis private;; procedureprocedure Swap (X, Y :Swap (X, Y : in outin out T);T); procedureprocedure Swap (X, Y :Swap (X, Y : in outin out T)T) isis Temp : Temp : constantconstant T := X; T := X; beginbegin X := Y;X := Y; Y := Temp;Y := Temp; endend Swap; Swap;

Page 13: 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.

1313

Subprogram parametersSubprogram parameters

• A generic sorting routine should apply to any array whose components A generic sorting routine should apply to any array whose components are comparable, i.e. for which an ordering predicate exists. This class are comparable, i.e. for which an ordering predicate exists. This class includes more that the numeric types: includes more that the numeric types:

genericgeneric typetype TT is private;is private; -- type parameter-- type parameter with functionwith function “<“ (X, Y : T) “<“ (X, Y : T) returnreturn Boolean; Boolean; -- subprogram -- subprogram

parameterparameter typetype Arr Arr is arrayis array (Integer (Integer rangerange <>) <>) ofof T; T; -- type parameter-- type parameter procedureprocedure Sort (A : Sort (A : in outin out Arr); Arr);

procedureprocedure Sort(A: Sort(A: in outin out Arr) is Arr) is -- A Procedure Body-- A Procedure Body Min: Index;Min: Index;

Temp : T;Temp : T; -- Using type parameter-- Using type parameter beginbegin

forfor I I in in A’first .. Index’Pred(A’Last) A’first .. Index’Pred(A’Last) looploop Min := I;Min := I;

forfor J J in in Index’Succ(I) .. A’Last Index’Succ(I) .. A’Last looploop if if A(J) < A(Min) A(J) < A(Min) thenthen Min := J; Min := J; end ifend if; ; -- Using subprogram -- Using subprogram

parameterparameter end loopend loop;; Temp := A(I); A(I) := A(Min); A(Min) := Temp; Temp := A(I); A(I) := A(Min); A(Min) := Temp; -- swap-- swap end loopend loop;; endend Sort; Sort;

Page 14: 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.

1414

Supplying subprogram Supplying subprogram parametersparameters

• The actual must have a matching signature, not The actual must have a matching signature, not

necessarily the same name:necessarily the same name:

• -- instantiate ascending and descending sort for integers-- instantiate ascending and descending sort for integers procedureprocedure Sort_Up Sort_Up is newis new Sort (Integer, “<“, …); Sort (Integer, “<“, …); procedureprocedure Sort_Down Sort_Down is newis new Sort (Integer, “>”, … ); Sort (Integer, “>”, … );

• -- instantiate sort by seniority for employees-- instantiate sort by seniority for employees typetype Employee Employee is record .. end recordis record .. end record;; functionfunction Senior (E1, E2 : Employee) Senior (E1, E2 : Employee) returnreturn Boolean; Boolean; functionfunction Rank Rank is newis new Sort (Employee, Senior, …); Sort (Employee, Senior, …);

Page 15: 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.

1515

Value parametersValue parameters

Useful to Useful to parametrizeparametrize containers by size: containers by size: genericgeneric typetype Elem Elem is privateis private; ; -- type parameter-- type parameter Size : Positive;Size : Positive; -- value parameter-- value parameter packagepackage Queues Queues isis typetype Queue Queue is privateis private;; procedureprocedure Enqueue (X : Elem; On : Enqueue (X : Elem; On : in outin out Queue); Queue); procedureprocedure Dequeue (X : Dequeue (X : outout Elem; From : Elem; From : in outin out Queue); Queue); functionfunction Full (Q : Queue) Full (Q : Queue) returnreturn Boolean; Boolean; functionfunction Empty (Q : Queue) Empty (Q : Queue) returnreturn Boolean; Boolean; privateprivate typetype Contents Contents is arrayis array (Natural (Natural rangerange <>) <>) ofof Elem; Elem; -- indefinite-- indefinite typetype Queue Queue is recordis record Front, Back: Natural;Front, Back: Natural; C : Contents (0 .. Size); C : Contents (0 .. Size); -- An array of the specified size-- An array of the specified size endend recordrecord;; endend Queues; Queues;

Small_Integer_Queue_Package Small_Integer_Queue_Package is newis new Queues(Integer, 10); Queues(Integer, 10);

Page 16: 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.

1616

Packages as parametersPackages as parameters

If interface includes a type and its operations, the If interface includes a type and its operations, the parameter can be a single generic package:parameter can be a single generic package:

genericgeneric typetype Real Real is digitsis digits <>; <>; -- any floating type-- any floating type packagepackage generic_complex_types generic_complex_types isis -- complex is a record with two real components-- complex is a record with two real components -- package declares all complex operations: +, -, -- package declares all complex operations: +, -,

Re, Im...Re, Im... endend generic_complex_types; generic_complex_types;

We also want to define a package for We also want to define a package for elementary functionselementary functions (sin, cos, etc.) on complex numbers. We need the complex (sin, cos, etc.) on complex numbers. We need the complex operations, which are parametrized by the corresponding operations, which are parametrized by the corresponding real value.real value.

Page 17: 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.

1717

The instantiation requires an The instantiation requires an instance of the parameterinstance of the parameter

withwith generic_complex_types; generic_complex_types; genericgeneric with packagewith package compl compl is newis new generic_complex_types generic_complex_types

(<>);(<>); packagepackage generic_complex_elementary_functions is generic_complex_elementary_functions is -- trigonometric, exponential, hyperbolic functions.-- trigonometric, exponential, hyperbolic functions. endend generic_complex_elementary_functions; generic_complex_elementary_functions;

Instantiate complex types with Instantiate complex types with long_floatlong_float componentscomponents::

packagepackage long_complex long_complex is newis new generic_complex_type generic_complex_type ((long_floatlong_float););

Instantiate complex functions for Instantiate complex functions for long_complexlong_complex types:types:

packagepackage long_complex_functions long_complex_functions isis newnew generic_complex_elementary_functions generic_complex_elementary_functions

((long_complexlong_complex););

Page 18: 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.

1818

Generics in C++ Generics in C++ (Templates)(Templates)

Template is a parameterized class or function Template is a parameterized class or function definitiondefinition

Compiler creates a separate class or function Compiler creates a separate class or function definition for each unique set of parameters with definition for each unique set of parameters with which it is instantiatedwhich it is instantiated Same code not used for multiple typesSame code not used for multiple types Originally implemented using macrosOriginally implemented using macros

Simple SyntaxSimple Syntax templatetemplate ‘ ‘<<‘ parameters ‘‘ parameters ‘>>’ class_def | func_def’ class_def | func_def Parameters may be types or valuesParameters may be types or values

Page 19: 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.

1919

A Template in C++A Template in C++ templatetemplate < <classclass T> T> classclass Vector { Vector { publicpublic:: Vector (size_t n); Vector (size_t n); // constructor// constructor T& T& operator [ ]operator [ ] (size_t index); (size_t index); // subscript operator// subscript operator privateprivate:: … … // implementation details// implementation details };}; Vector<Vector<intint> V1 (100); > V1 (100); // instantiation// instantiation typedeftypedef Vector<Employee> Dept; Vector<Employee> Dept; // named type // named type

instanceinstance

Page 20: 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.

2020

Class and value parametersClass and value parameters templatetemplate < <classclass T, T, intint i> i> classclass Buffer { Buffer { T v [i]; T v [i]; -- storage for buffer-- storage for buffer intint sz; sz; -- total capacity-- total capacity intint count; count; -- current contents-- current contents publicpublic:: Buffer(Buffer( ) : sz (i) , count (0) { };) : sz (i) , count (0) { }; T read ();T read (); voidvoid write (T elem); write (T elem); }; }; Buffer <Shape, 100> picture; Buffer <Shape, 100> picture; -- instance for a -- instance for a

graphics graphics app.app.

Page 21: 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.

2121

Template hopes for the bestTemplate hopes for the best

templatetemplate < <classclass T> T> classclass List { List { structstruct Link { Link { // for a list node// for a list node Link* pre; Link* pre; // doubly linked// doubly linked Link* succ;Link* succ; T val;T val; Link (Link* p, s, Link (Link* p, s, constconst T& v): pre (p), succ(s), val (v) T& v): pre (p), succ(s), val (v)

{ }; }{ }; } Link * head;Link * head; public:public: voidvoid print_all () { print_all () { forfor (Link*p = head; p; p=p->succ) (Link*p = head; p; p=p->succ) cout << p -> cout << p -> valval << ‘\n’; << ‘\n’;

// operator<< better exist for T!// operator<< better exist for T! };};

Page 22: 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.

2222

Function templatesFunction templates

Instantiated implicitly at point of first Instantiated implicitly at point of first call.call.

templatetemplate < <classclass T> T> voidvoid sort (vector <T>& v) sort (vector <T>& v) {..};{..};

voidvoid testit (vector< testit (vector<intint>& vi) {>& vi) {

sort (vi);sort (vi);

// can also write sort<int> (vi);// can also write sort<int> (vi);

};};

Page 23: 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.

2323

Functions and function Functions and function templatestemplates

Templates and regular functions overload Templates and regular functions overload each othereach other::

templatetemplate < <classclass T> T> classclass complex {…}; complex {…};

templatetemplate < < classclass T> T sqrt (T); T> T sqrt (T); // function template for // function template for any Tany T

templatetemplate < < classclass T> complex <T> sqrt (complex <T>); T> complex <T> sqrt (complex <T>); // // specializationspecialization

double double sqrt (sqrt (doubledouble); ); // regular function// regular function voidvoid testit (complex< testit (complex<doubledouble> cd) {> cd) { sqrt (2); sqrt (2); // sqrt<int>:// sqrt<int>: specialization of templatespecialization of template sqrt (cd); sqrt (cd); // sqrt(<double>(complex<double>): // sqrt(<double>(complex<double>):

specializationspecialization sqrt (2.0); sqrt (2.0); // sqrt (double):// sqrt (double): regular functionregular function };};

Page 24: 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.

2424

Iterators and ContainersIterators and Containers Containers are standard data structures to manage Containers are standard data structures to manage

collectionscollections Arrays, Linked Lists, Balanced Trees, etc.Arrays, Linked Lists, Balanced Trees, etc. Operations include: insert, delete, search, countOperations include: insert, delete, search, count

Standard algorithms over collections use iterators:Standard algorithms over collections use iterators:

templatetemplate < <classclass Coll, Coll, classclass Elem> Iterator { Elem> Iterator { Iterator (Coll over) { ..}; Iterator (Coll over) { ..}; // build iterator for given // build iterator for given

collectioncollection Elem First_Elem (); Elem First_Elem (); // start iteration// start iteration Elem Next_Elem (); Elem Next_Elem (); // move to next element in // move to next element in

collectioncollection boolbool done (); done (); // termination condition// termination condition }; };

Page 25: 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.

2525

Standard Template LibraryStandard Template Library Generic Library for C++Generic Library for C++

Well-structured componentsWell-structured components Orthogonal designOrthogonal design Based on firm theoretical foundationsBased on firm theoretical foundations Efficient implementationEfficient implementation

Components Components Algorithms – define computational proceduresAlgorithms – define computational procedures Containers – manage a set of objectsContainers – manage a set of objects Iterators – means of traversing containers Iterators – means of traversing containers Function Objects – encapsulate functions in Function Objects – encapsulate functions in

objectsobjects Adaptors – adapts components to provide a Adaptors – adapts components to provide a

different interfacedifferent interface

Page 26: 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.

2626

Common Operators Common Operators

STL defines STL defines !=!=, , >>, , >=>=, , <=<= from from ==== and and << templatetemplate < <classclass T> T> inline boolinline bool operator!=operator!= ((constconst T& x, T& x, constconst T& y) { T& y) { returnreturn !(x == y); }!(x == y); }

templatetemplate < < classclass T> T> inline boolinline bool operator>=operator>= ( (constconst T& x, T& x, constconst T& y) { T& y) { returnreturn !(x < y); } !(x < y); }

Programmer only needs to define Programmer only needs to define ==== and and <<

Sound and logically consistent semanticsSound and logically consistent semantics

Page 27: 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.

2727

STL AlgorithmsSTL Algorithms Algorithms operate on iteratorsAlgorithms operate on iterators

Apply a function to every element in a containerApply a function to every element in a containertemplatetemplate < <classclass iter, iter, classclass function> function> voidvoid for_each(iter first, iter last, function f); for_each(iter first, iter last, function f); APL-like Reduction APL-like Reduction templatetemplate < <classclass iter, iter, classclass T, T, classclass bin_op> bin_op> voidvoid accumulate(iter first, iter last, T init, function f); accumulate(iter first, iter last, T init, function f);

OrthogonalOrthogonal Algorithm can operate on any container that Algorithm can operate on any container that

supports basic iteratorssupports basic iterators The actual iterator provided may be more complex The actual iterator provided may be more complex

Page 28: 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.

2828

STL ContainersSTL Containers Sequence, list, dequeue, set, map, string, etc.Sequence, list, dequeue, set, map, string, etc.

Instantiated with type parameterInstantiated with type parametertypedeftypedef list<int> int_list; list<int> int_list;int_list a_list;int_list a_list;

All access is based on iteratorsAll access is based on iterators Containers include standard iterators:Containers include standard iterators:

begin() begin() // returns iterator pointing to first element in container// returns iterator pointing to first element in container end() end() // returns iterator pointing to first location after end of // returns iterator pointing to first location after end of

containercontainer Allows uniform access to all kinds of containersAllows uniform access to all kinds of containers

forfor (c.iterator I = c.begin(); I != c.end(); ++I) { (c.iterator I = c.begin(); I != c.end(); ++I) { … … }}

Page 29: 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.

2929

STL IteratorsSTL Iterators Iterators are a generalization of the semantics of Iterators are a generalization of the semantics of

pointerspointers (and arrays) in C (and arrays) in C Categories of iteratorsCategories of iterators

Input Input OutputOutput ForwardForward BidirectionalBidirectional Random AccessRandom Access

Operations on Iterators include:Operations on Iterators include: =, ==, !=, ++(pre and post), *(dereference)=, ==, !=, ++(pre and post), *(dereference) Bidirectional iterators also support: --(pre and post), +, -, Bidirectional iterators also support: --(pre and post), +, -,

etc. etc.

Page 30: 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.

3030

Function Class and AdaptorsFunction Class and Adaptors Function classes are classes for which the Function classes are classes for which the

operator () is defined, allowing the object itself to operator () is defined, allowing the object itself to be called as a functionbe called as a function // A function of type int // A function of type int bool bool unary_function<int, bool> unary_function<int, bool>

// A function of type (int x int) // A function of type (int x int) bool bool binary_function<int, int, bool>binary_function<int, int, bool>

Adaptors allow a particular interface to be Adaptors allow a particular interface to be wrapped around an object.wrapped around an object. Stack adaptor can be supported by a vector, list or Stack adaptor can be supported by a vector, list or

deque.deque. Stack<vector> myStack;Stack<vector> myStack;

Page 31: 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.

3131

Using STLUsing STLmainmain (int argc, char *argv[]) { (int argc, char *argv[]) { int *last; int *last; // integer iterator// integer iterator int result;int result; int test_seq[20];int test_seq[20]; // space for test data// space for test data last = test_seq + 20;last = test_seq + 20; ostream_iterator<int> out_stream(cout, “”);ostream_iterator<int> out_stream(cout, “”); // use generic library functions, such as IotaGen (like APL // use generic library functions, such as IotaGen (like APL

iota) to generate test dataiota) to generate test data generate(test_seq, last, IotaGen<int>(0));generate(test_seq, last, IotaGen<int>(0)); copy(test_seq, last, out_stream);copy(test_seq, last, out_stream); // output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19// output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 result = accumulate(test_seq, last, 0);result = accumulate(test_seq, last, 0); cout << result << endl;cout << result << endl; // 190// 190}}

Page 32: 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.

3232

GJ and PizzaGJ and Pizza Added ML style Generics to JavaAdded ML style Generics to Java

Based on type inference in MLBased on type inference in ML Ensures no run-time errorsEnsures no run-time errors Allows same code to execute for different Allows same code to execute for different

typestypes Syntax similar to C++ TemplatesSyntax similar to C++ Templates Compatible with legacy JavaCompatible with legacy Java New Container LibrariesNew Container Libraries Based on GJ and PizzaBased on GJ and Pizza

Research at Bell Labs and ElsewhereResearch at Bell Labs and Elsewhere Phillip WadlerPhillip Wadler

Page 33: 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.

3333

Generic JavaGeneric Java Bad old ugly JavaBad old ugly Java

VectorVector v = v = newnew VectorVector(10);(10); v.put(Integer(9));v.put(Integer(9)); v.put(String(“abc”));v.put(String(“abc”)); StringString s = (String) v.get(n); s = (String) v.get(n); // Run-time error if // Run-time error if

object is not a string!object is not a string! Good new elegant Java 1.5Good new elegant Java 1.5

Vector<String>Vector<String> v = v = newnew Vector<String>Vector<String>(10);(10); v.put(Integer(9)); v.put(Integer(9)); // Compile time error// Compile time error v.put(String(“abc”));v.put(String(“abc”)); StringString s = v.get(n); s = v.get(n); // No cast required// No cast required

Page 34: 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.

3434

Creating Generic ClassesCreating Generic Classespublicpublic classclass Stack<T> { Stack<T> { Vector<T> store;Vector<T> store; // Actual storage structure// Actual storage structure

publicpublic Stack(int n) {store = Stack(int n) {store = newnew Vector<T>(n);} Vector<T>(n);}publicpublic Stack() {store = Stack() {store = newnew Vector<T>(10);} Vector<T>(10);}

publicpublic void Push(T e) { store.add(e);} void Push(T e) { store.add(e);} // Only accepts elements of // Only accepts elements of type Ttype T

publicpublic T Pop() { T Pop() { // Returns type T// Returns type T ifif (store.isEmpty()) { (store.isEmpty()) { throw newthrow new StackEmptyException() StackEmptyException() } } elseelse { { returnreturn remove(store.size-1); remove(store.size-1);} } }} } }

Page 35: 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.

3535

Using Generic ClassesUsing Generic Classes

Stack<int> si; Stack<int> si; // Create an integer stack// Create an integer stack Stack<String> ss;Stack<String> ss;

si.push(4); si.push(4); // OK, si is integer stack// OK, si is integer stack ss.push(“Hello”); ss.push(“Hello”); // OK, ss is string stack// OK, ss is string stack ss.push(3); ss.push(3); // Compile time error// Compile time error

int i = si.pop(); int i = si.pop(); // No cast, no runtime error// No cast, no runtime error


Recommended