Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
1111 Abstract Data Types Cpt S 223. School of EECS, WSU.
Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Chapter 12 Separate Compilation and Namespaces. Abstract Data Type (ADT) ADT: A data type consisting of data and their behavior. The abstraction is that.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Vectors, lists and queues
Addressing the Challenges of Current Software. Questions to Address Why? What? Where? How?
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
Templates in C++. Generic Programming Programming/developing algorithms with the abstraction of types The uses of the abstract type define the necessary.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Lecture 3 Introduction to Collections Advanced Java Programming 1 dr inż. Wojciech Bieniecki
C/c++ 4 Yeting Ge.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Generic Programming David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Abstract data types & object-oriented paradigm. Abstraction Abstraction: a view of an entity that includes only the attributes of significance in a particular.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
Object Oriented Data Structures
Introduction to Object-oriented programming and software development Lecture 1.
Data Structures Lecture-12 : STL Azhar Maqsood NUST Institute of Information Technology (NIIT)
FALL 2001ICOM Lecture 21 ICOM 4015 Advanced Programming Lecture 2 Procedural Abstraction Reading: LNN Chapter 4, 14 Prof. Bienvenido Velez.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Useful Data Structures in C++ and Java. Useful Data Structures in C++ (1) Templates are C++’s mechanism to define abstract objects which can be parameterized.
OBJECT-ORIENTED PROGRAMMING (OOP) WITH C++ Instructor: Dr. Hany H. Ammar Dept. of Electrical and Computer Engineering, WVU.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
111/15/2015CS150 Introduction to Computer Science 1 Summary  Exam: Friday, October 17,  Assignment: Wednesday, October 15, 2003  We have completed.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
CS342 Data Structures End-of-semester Review S2002.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
Overview of C++ Templates
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Vectors the better arrays. Why Vectors l vectors are implemented as a class (a template to be exact) l they serve the same purpose as arrays but using.
Copyright © Curt Hill STL Priority Queue A Heap-Like Adaptor Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
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.
C++ REVIEW – TEMPLATES. GENERIC PROGRAMMING Programming/developing algorithms with the abstraction of types Algorithms/data is expressed “without type”
CS212: Object Oriented Analysis and Design
Programming what is C++
Deitel- C:How to Program (5ed)
CS212: Object Oriented Analysis and Design
Object-Oriented Programming (OOP) Lecture No. 32
Reference Variables The symbol “&” has a few different purposes depending on where it occurs in code. When it appears in front of a variable name, it is.
Modular Programming with Functions
Introduction to Programming
Template Functions Lecture 9 Fri, Feb 9, 2007.
Presentation transcript:

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică

2Programming IIObject-Oriented Programming Course #8 Agenda Generic Programming (Templates) Introduction From abstract to generic types Class templates and template instantiation Function templates Specialization

3Programming IIObject-Oriented Programming Introduction Express algorithms independently of representation details Generic Programming = Decide which algorithms you want; parameterize them so that they work for a variety of suitable types and data structures. DEFINITION [Template, Parameterized data type] A template represents a family of types or functions, parameterized by a generic type. Benefits –Increased code reusability (e.g. generic lists/containers, generic sorting algorithms etc.) –Allow design and implementation of general purpose libraries (e.g. math libraries, data structures etc.)

4Programming IIObject-Oriented Programming From abstract to generic types Example: // vector of integers class vector { int *v; int size; public: vector( ): v(NULL),size(0) { } int get(int n) { return v[n]; } void add(int x); }; void f( ) { vector v ; v.add(1) ; v.add(100); cout << v.get (0); } // vector of floats class vector { float *v; int size; public: vector( ): v(NULL),size(0) { } float get(int n) { return v[n]; } void add(float x); }; void f( ) { vector v ; v.add(1.56) ; v.add( ); cout << v.get (0); }

5Programming IIObject-Oriented Programming From abstract to generic types (II) Declaration of template class template class vector { T *v; int size; public: vector( ): v(NULL), size(0) { } T get(int n) { return v[n]; } void add( T x); }; void f( ) { vector v; v.add(1) ; v.add(100); cout << v.get (0); vector fv; fv.add(2.5); } Usage of template class (template instantiation) Implementation template void vector ::add(T e) { // add e to the vector v }

6Programming IIObject-Oriented Programming Class templates Syntax template Declaration List-of-parameters – a comma separated list of template’s parameters – type parameters (class T): T may be initialized with a primitive type (int, char, float), a user- defined type (MyClass, complex etc.), a pointer type (void *, etc), a reference type (int&, MyClass&) or a template instantiation – non-type parameters (int i): non-type parameters can be instantiate only with constant values and are constant in type declaration/definition. Declaration – declaration/definition of function or class – definition of a static member of a template – definition of a class/function member of a template – definition of a template member of an ‘ordinary’ class Example: Declaration of class template template class ClassName { // class declaration };

7Programming IIObject-Oriented Programming Template instantiation DEFINITION [Template instantiation] The process of generating a class definition from a template class is called template instantiation. Syntax: Examples: TemplateClass vector d1; vector d2; Buffer d3; d1 = d2; The compiler will generate ordinary classes for instantiated types. Also, ordinary C++ functions are generated only for used functions of instantiated templates. If no template instantiation is made then nothing is generated. Example: for d1 – class vector + default constructor, destructor, assignment operator

8Programming IIObject-Oriented Programming Type checking Errors in template definition: ones that can be detected at point of definition (=compilation time), e.g. missing semicolon or misspelled keyword; others that can be detected only at template instantiation. DEFINITION [Point of instantiation] The first instantiation of a template is called point of instantiation and it has an important role in finding out and fixing template errors. The arguments passed in for a template instantiation have to support the expected public interface of that type. class X { }; template void vector ::add(T e) { // add e to the vector v cout << “Added element “ << e; } void f() { vector v; // instantiation v.add(X()); // => error! Why? } For debugging purpose, use the most frequent types as arguments for type parameters..

9Programming IIObject-Oriented Programming Type equivalence The following types are equivalent: Example: Buffer template template class Buffer { T buffer [i]; int size; public: Buffer() : size(i) { } // error: being constant, i cannot be modified void f( ) {i=10;} }; typedef unsigned char UCHAR ; Buffer  Buffer  Buffer The following types are not equivalent: Buffer is not equivalent to Buffer because ‘unsigned char’ and ‘char’ are not the same type. void f() { Buffer b1; //  char buffer[100]; Buffer b2; //  void * buffer[190]; int N=10; Buffer b; // => error; N is not constant } Non-type parameters

10Programming IIObject-Oriented Programming Remarks A template class may have three types of friends : –Non-template class/function –Template class/function –Template class/function with a specified type (specialization template). Static members: each instance has its own static data. Use typedef for frequently used templates. typedef vector string; typedef Buffer Buffer100;

11Programming IIObject-Oriented Programming Function templates (I) Example: int min(int x, int y) { return x<y ? x : y; } float min(float x, float y) { return x<y ? x : y; } complex min(complex x, complex y) { // … } void f() { complex c1(1,1), c2(2,3); min(0,1); min(6.5, 3); min(c1, c2); } template T min(T x, T y) { return x<y ? x : y; } void f() { complex c1(1,1), c2(2,3); min(0,1);  min (0,1); min (6.5, 3); min(c1, c2);  min (c1,c2); } Template version of min function Remark: The operator < has to be overloaded for complex class.

12Programming IIObject-Oriented Programming Function templates (II) Syntax template function_declaration; Template function instantiation is similar to class instantiation. Examples: –min (0, 1); –min (...); If the arguments type uniquely identify the parameter type then the compiler will automatically do the instantiation so that the programmer doesn’t have to explicitly instantiate the function. Examples: min(0,1); // okay min(2.5, 3); // ambiguous; need explicit qualification min (2.5, 3); min (2.5, 3); // okay To resolve ambiguities: —Use explicit qualification —User overloading/specialization to add new functions that match the call (e.g. min(double, int))

13Programming IIObject-Oriented Programming Function template overloading If someone needs a custom version of a template function or of a member function of a template class, then that function can be overloaded for that particular type. template T sqrt(T); template complex sqrt(complex ); double sqrt(double); void f(complex c) { c = sqrt(c ); double d = sqrt(49.0); int x = sqrt(49); } Function overload resolution rules: 1.Find the set of function templates specializations. 2.If two template functions can be called then select the most specialized one for next step. 3.Do overload resolution for this set of functions, plus any ordinary functions as for ordinary functions. 4.If a function and a specialization are equally good matches, the function is preferred. 5.If no match is found then the call is an error. Remark: If the template function has parameters of a type that is not defined as template parameter, then this parameters are handled as any other ‘ordinary’ C++ function parameter (for example, various possible conversion are applied).

14Programming IIObject-Oriented Programming Specialization (I) DEFINITION [Specialization] Alternative definitions of a template for a particular type of template parameters are called user specializations. Example: Template vector. A lot of vector instances will be created => code bloat (unnecessarily long, slow and wasteful of resources) Solution: Containers of pointers can share the same implementation expressed through specialization. // specialization for void* template<> class vector { void** p; void*& operator[] (int i); //…. }; void f () { vector v; // use specialization version } Corollary: Specialization is a way of specifying alternative implementations for different uses of a common interface.

15Programming IIObject-Oriented Programming Specialization (II) Partial specialization // partial specialization for T* template class vector : private vector { public: typedef vector Base; vector() : Base() {} explicit vector(int i) : Base(i) { } T*& elem(int i) { return static_cast (Base::elem(i)); } T*& operator[](int i) { return static_cast (Base::operator[](i)); }; Remark: Only derivation and inline functions are defined in the partial specialization template. Order of specialization Remarks: 1.General template must be declared before any specialization. 2.The specialization must be in the scope for every use of the template with the type for which it was specialized. 3.The most specialized version will be preferred over the others. // remark 1 template class List { } ; // remark 2 template class List {} ; List li; Template class List {};

16Programming IIObject-Oriented Programming Template function specialization Template function specialization is appropriate when there is a more efficient alternative to a general algorithm for a set of template arguments. Example: sorting vectors template bool less(T a, T b) { return a < b; } template void sort(vector & v) { // … if(less(v[j], v[k]) swap(v[j], v[k]); } vector vc; sort(vc); // will not sort correctly the vector; why? Solution: specialize less function for char* template<> bool less (const char* a, const char* b) { return strcmp(a,b) < 0; } // or equivalently with template<> bool less(const char* a, const char* b) { return strcmp(a,b) < 0; }

17Programming IIObject-Oriented Programming Further Reading [Pop, 2003] Daniel Pop – C++ Programming Language Lecture Notes [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 13][Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 13]