1 159.234LECTURE 17 159.234 LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

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 9 Imperative and object-oriented languages 1.
Chapter 14: Overloading and Templates
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Classes: A Deeper Look Systems Programming.
Rossella Lau Lecture 5, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 5: Class construction  Encapsulation 
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles C/C++ Emery Berger and Mark Corner University of Massachusetts.
Lecture 9 Concepts of Programming Languages
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
1 CSC241: Object Oriented Programming Lecture No 07.
Review of C++ Programming Part II Sheng-Fang Huang.
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.
Intro to Generic Programming Templates and Vectors.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CS 11 C++ track: lecture 7 Today: Templates!. Templates: motivation (1) Lots of code is generic over some type Container data types: List of integers,
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Programming Languages and Paradigms Object-Oriented Programming.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
C++ Review (3) Structs, Classes, Data Abstraction.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
1 CSC241: Object Oriented Programming Lecture No 25.
Overview of C++ Templates
Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
PROGRAMMING 1 – HELPER INSTRUCTIONS ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
MAITRAYEE MUKERJI Object Oriented Programming in C++
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Motivation for Generic Programming in C++
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Templates.
Operator overloading Conversions friend inline
Review: Two Programming Paradigms
Templates.
Lecture 9 Concepts of Programming Languages
Constructors and destructors
Constructors and Destructors
Parameter Passing Actual vs formal parameters
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Lecture 9 Concepts of Programming Languages
Presentation transcript:

LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.

2Templates Some Terms Function Template 19 A function template is a template used to generate functions. Template Function A template function is a function that is produced by a template. i = Max(j,k); template T Max(T x, T y) { if (x > y) return x; else return y; } e.g. This function call tells the compiler to generate the actual template function.

3Templates Some Terms Class Template 19 A class template is a template that is used to generate classes. Template Class A template class is a class that is produced by a template. template class Vector{ //class interface }; e.g. Vector m(100); Vector d(200); Actual template class

4TemplatesFriends 19 template class matrix{ public: friend void foo_bar(); //universal friend vect product(vect v); //instantiated }; A friend function that does not use a template specification is universally a friend of all instantiations of the template class. A friend function that incorporates template arguments is specifically a friend of its instantiated class.

5Templates Static Members 19 template class Vect{ public: static int count; //… }; Static members are not universal but are specific to each instantiation. Static variables Vect ::count and Vect ::count are distinct. Vect a; Vect b;

6Templates Default Template Arguments 19 template class Vect{ public: //… }; You can assign a default type to your class template Vect a; Vect b; Default type Instantiation:

7Templates Member Templates 19 template class Vect{ public: template class Complex{ //… //can use T1 and T2 in Complex }; //can only use T1 in Vect }; Members may themselves be templates inside the template class. Vect ::Complex a; class member template New feature of ANSI standard - yet to be implemented on most C++ compilers

8 1. Not using template when defining member function for class templates. 2. Not using the generic type for parameters/variables. 3. Not placing class, before every formal type parameter. Correct: template If a template is invoked with a user defined class type and that template uses operators (==, +, <=, etc.) with objects of that class type, then those operators must be overloaded. Common Errors with Templates

9 Macros present the possibility of having side effects because they do not usually have type checking. #define SQ(A) ((A)*(A)) template T square (T x){ return x*x; } Templates vs. Macros

10 int main(){ int a = 7; cout<<square(a++)<<endl; cout<<"and a is "<<a<<endl; cout <<SQ(a++)<<endl; cout<<"and a is "<<a<<endl; } /*output: 49 and a is 8 64 and a is 10 */ Templates vs. Macros #define SQ(A) ((A)*(A)) template T square (T x){ return x*x; }

11Templates Class Template Example Vector Class Template 19 Vector() ~Vector() operator=() operator[] Size() See VectorT.cpp copy() public: protected: Vector Vector Vector() ~Vector() operator=() operator[] Size() copy() Instantiated from the Class template size data x size data y xy x & y are both instantiated from the Template class Vector Cannot Cannot be invoked by any of the class instances

12Templates SubClass Template Example Vector Class Template 19 Vector() ~Vector() operator=() operator[] Size() copy() public: protected: e.g. Instead of the range [0, 100], we want to have [1, 100], or even [-100, 100]. What if we want to allow the user to designate the range of indexes for the Vector class? We can derive a new class that could Inherit all the functionalities of Vector, as well as perform some modifications.

13 Nested Templates Passing Template Classes to Template Parameters Array Class Template 19 template public Vector class Array : public Vector { public: i0 Array(int i, int j) : Vector (j-i+1), i0(i) {} i0 Array(const Array & v) : i0(v.i0), Vector (v) {} Vector ::operator[](i-i0); T& operator[](int i) const { return Vector ::operator[](i-i0);} i0 int firstsubscript() const {return i0;} i0 int lastsubscript() const {return i0 + Vector ::size - 1;} protected: int i0 int i0; //index 0 (or first index number) }; Array class template connects to the Vector class template via inheritance. See Subclass Template for Vectors.cpp Explicitly calls the Vector operator[]

14Templates Class Template Example What if we want to allow for an ordinary array to be replicated as a vector? 19 See Replicating an ordinary array as a vector.cpp int a[] = {11, 22, 33, 44, 55}; Vector v(a);

15 // multidimensional_arrays.cpp // compile with: /EHsc // arguments: 3 #include // Includes DBL_MAX #include const int cMkts = 4, cFacts = 2; // Declare a float that represents the transportation costs double TransportCosts[][cMkts] = { { 32.19, 47.29, 31.99, }, { 11.29, 22.49, 33.47, }, { 41.97, 22.09, 9.76, } }; // Calculate size of unspecified dimension const int cFactories = sizeof TransportCosts / sizeof( double[cMkts] );

16 Nested Templates Passing Template Classes to Template Parameters Our own class templates can accept built-in classes as template parameter: 19 See Matrix.cpp Vector a; Since template classes work like ordinary classes, we can also pass them to template parameters: Stack > b; Array > > c;

17 Nested Templates Passing Template Classes to Template Parameters Matrix – essentially a 2D vector 19 See Matrix.cpp It can be represented as a 2-element Vector, each of whose elements is a 3-element Vector: a 2-by-3 Matrix is a table with 2-rows & 3-columns This representation would allow us to use our Vector class template to define a new Matrix class template.

18 Nested Templates Passing Template Classes to Template Parameters To facilitate dynamic allocation of memory, we define a Matrix as a Vector of Pointers to Vectors 19 See Matrix.cpp When the Matrix class template is instantiated, the Instances of the resulting class will contain vectors of pointers to vectors. Vector * >

19 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template 19 See Matrix.cpp template class Matrix{ public: Matrix(unsigned r=1, unsigned c=1) : row(r) {//… } ~Matrix(){ //… } Vector & operator[](unsigned i) const {//… } unsigned rows() {return row.size(); } unsigned columns() {return row[0]->size(); } //(*row).size() protected: Vector *> row; }; Vector of pointers to Vectors Matrix class template connects to the Vector class template via composition.

20 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template : Constructor 19 See Matrix.cpp Matrix(unsigned r=1, unsigned c=1) : row(r) { for(int i=0; i < r; i++) { row[i] = new Vector (c); }

21 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template : Destructor 19 See Matrix.cpp ~Matrix(){ for(int i=0; i < row.Size(); i++) { delete row[i]; }

22 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template : Subscripting Operator 19 See Matrix.cpp Vector & operator[](unsigned i) const { return *row[i]; } unsigned rows() {return row.Size(); } unsigned columns() {return row[0]->Size(); } //(*row).size()

23 Nested Templates Passing Template Classes to Template Parameters Creating an Instance of the Matrix Class Template : 19 See Matrix.cpp Matrix a(2, 3); data size= data size= Vector row size=2 0 1 Matrix a Matrix() ~Matrix() operator[] rows() columns() Matrix Vector of pointers to Vectors

24 Nested Templates Extracting an element of the Matrix Template Class a: 19 See Matrix.cpp a[1][2] data size= data size= Vector row size=2 0 1 Matrix a Matrix() ~Matrix() operator[] rows() columns() Matrix Matrix operator[1] Vector operator[1] Vector operator[2] invokes the following operators: Matrix operator[1] Vector operator[1] data[i] = 0x4d3f58 Vector operator[2] data[i] = 1.2 m[1][2] = 1.2

25 Nested Templates Extracting an element of the Matrix Template Class a: 19 See Matrix.cpp, Matrix_stl.cpp a[0][2] data size= data size= Vector row size=2 0 1 Matrix a Matrix() ~Matrix() operator[] rows() columns() Matrix Matrix operator[0] Vector operator[0] Vector operator[2] invokes the following operators:

26 C++ uses templates to provide generic programming. Templates are one of C++’s features that allow for software reuse. By allowing the user of the class template to provide the data type through the specification of the type parameter during instantiation, the same code can be utilized for different types.Summary

27 A large collection of reusable components. The key components of the STL -- containers are data structures created using templates. A container is an object that contain objects. Using STL can save considerable time and effort, and result in higher quality programs. Standard Template Library (STL)