Templates. C++ 2 Outline Function templates  Function template definition  Function template overloading Class templates  Class template definition.

Slides:



Advertisements
Similar presentations
Engineering Problem Solving With C++ An Object Based Approach Additional Topics Chapter 10 Programming with Classes.
Advertisements

Operator overloading redefine the operations of operators
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Derived Classes. C++ 2 Outline  Definition  Virtual functions  Virtual base classes  Abstract classes. Pure virtual functions.
1 Stacks Chapter 4. 2 Objectives You will be able to: Describe a stack as an ADT. Build a dynamic-array-based implementation of stacks. Build a linked-list.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Operator Overloading Programming in C++ Fall 2008 Dr. David A. Gaitros
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
CMSC 2021 Stream I/O Operators and Friend Functions.
Definition Class In C++, the class is the construct primarily used to create objects.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
 2006 Pearson Education, Inc. All rights reserved Generics.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
CS 1031 C++: Object-Oriented Programming Classes and Objects Template classes Operator Overloading Inheritance Polymorphism.
1 CSC241: Object Oriented Programming Lecture No 27.
CMSC 202 Lesson 23 Templates II. Warmup Write the templated Swap function _______________________________ void Swap( ________ a, ________ b ) { _______________.
What is a Stack? n Logical (or ADT) level: A stack is an ordered group of homogeneous items in which the removal and addition of items can take place only.
Templates Zhen Jiang West Chester University
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Case Study - Fractions Timothy Budd Oregon State University.
1 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
Basic Concepts of OOP in C++ Darvay Zsolt. C++ 2 Outline  The namespace and its members  The using declaration and directive  The address operator.
J. P. Cohoon and J. W. Davidson © 1997 McGraw-Hill, Inc. Templates Generic functions and classes.
C ++ Basics by Bindra Shrestha sce.uhcl.edu/shresthab CSCI 3333 Data Structures.
Exception Handling. C++ 2 Outline  Throwing and handling exceptions  Exceptions of different types  The new operator and the exceptions  Re-throwing.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Engineering Problem Solving with C++, Second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 5 Parameter Passing 11/06/13.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 22 - C++ Templates Outline 22.1Introduction.
Classes class A { ... };.
Data Structure Specification  Language independent  Abstract Data Type  C++  Abstract Class.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
1 COMS 261 Computer Science I Title: Classes Date: November 9, 2005 Lecture Number: 29.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
1 Introduction to Object Oriented Programming Chapter 10.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
Exception Handling How to handle the runtime errors.
17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Copyright © Curt Hill STL Priority Queue A Heap-Like Adaptor Class.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
The Class arrayList General purpose implementation of linear lists. Unknown number of lists.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Why exception handling in C++?
Name: Rubaisha Rajpoot
Introduction to Programming
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Introduction to Programming
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Template.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

Templates

C++ 2 Outline Function templates  Function template definition  Function template overloading Class templates  Class template definition  Class template objects

C++ 3 Function templates  If we would like to define a function in such a way as we should call it for different types of parameters, we can define a function template.  This template contains template parameters which will be substituted with real types, when calling the function.

C++ 4 Function Template Definition  We start the function definition with template where the list of parameters must be given in the form: class name_1, class name_2,..., class name_n  Thus, name_i can substitute a type.  The list of formal parameters of the function must contain all type parameters.

C++ 5 Example #include using namespace std; template void MySwap(T& a, T& b) { T x; x = a; a = b; b = x; }

C++ 6 The Print_Swap Function template void Print_Swap(T& a, T& b) { cout << "before swapping:\n"; cout << "a =" << a << "\t"; cout << "b =" << b << endl;

C++ 7 The Print_Swap Function MySwap(a, b); cout << "after swapping:\n"; cout << "a =" << a << "\t"; cout << "b =" << b << endl; }

C++ 8 The main Function int main() { int u = 3; int v = 5; Print_Swap(u, v); double y = 3.2; double z = 5.7; Print_Swap(y, z); }

C++ 9 Output before swapping: a =3 b =5 after swapping: a =5 b =3 before swapping: a =3.2 b =5.7 after swapping: a =5.7 b =3.2

C++ 10 Example 2 #include using namespace std; template void Display_Type(T a) { cout << a << "\t"; cout << typeid(T).name() << endl; }

C++ 11 The Fraction Class class Fraction { int numerator; int denominator; public: Fraction(int a, int b); ostream& Display(ostream &s) const; };

C++ 12 Constructor Fraction::Fraction(int a, int b) { numerator = a; denominator = b; }

C++ 13 The Display Function ostream& Fraction::Display(ostream &s) const { return s << numerator << " / " << denominator; }

C++ 14 Inserter Operator Overloading ostream& operator <<(ostream& s, const Fraction & t) { return t.Display(s); }

C++ 15 The main Function int main() { Display_Type(3); Display_Type(5.9); Fraction y(4, 9); Display_Type(y); }

C++ 16 Output 3 int 5.9 double 4 / 9 class Fraction

C++ 17 Function Template Overloading  If we don’t want to generate an issue of the function template for a specific list of parameters, then we can overload the function template.  This should be done by adding a conventional function to the code, which has exactly the required list of parameters.

C++ 18 Example (MySwap) #include using namespace std; //...

C++ 19 MySwap template void MySwap(T& a, T& b) { T x; x = a; a = b; b = x; cout << "With function template\n"; }

C++ 20 Allow Different Types template void Print_Swap(T1& a, T2& b) { cout << "before swapping:\n"; cout << "a =" << a << "\t"; cout << "b =" << b << endl; MySwap(a, b); cout << "after swapping:\n"; cout << "a =" << a << "\t"; cout << "b =" << b << endl; }

C++ 21 Overloading void MySwap(int& a, double& b) { int x; x = a; a = static_cast (b); b = x + fabs(b-a); cout << "Without a template\n"; }

C++ 22 The main function void main() { double y = 3.2; double z = 5.7; Print_Swap(y, z); int t = 7; double w = 10.9; Print_Swap(t, w); }

C++ 23 Output before swapping: a =3.2 b =5.7 With function template after swapping: a =5.7 b =3.2 before swapping: a =7 b =10.9 Without a template after swapping: a =10 b =7.9 Change only integer parts

C++ 24 Class Template Definition  Definition: template class ClassName { //... };  The list of parameters can contain type parameters and constant parameters.  The type parameters should be given in the form class name and the constant parameters as an ordinary declaration, in the form type name.

C++ 25 Member Function Definition  If the member functions are defined outside the class, then these should be function templates.  Thus, they should start with: template  After the class name we should give only the parameter names between the signs.

C++ 26 Example (member function) template class MyStack { T t[I]; public: //... void Push(T x); }; template void MyStack ::Push(T x){ //... }

C++ 27 Objects of the Class Template  When defining an object, after the class name one has to give the type parameters and the constant parameters.  Use the following form: classname object;  Example: MyStack v;

C++ 28 Example  Define the MyStack class template, with the Push and Pop member functions, and overload the inserter << operator such that all the elements should be take out from the stack. #include using namespace std;

C++ 29 The MyStack Class Template template class MyStack { T t[I]; int n; public: class FullStack {}; // exception

C++ 30 The MyStack Class Template class EmptyStack{}; //exception MyStack() { n = 0; } void Push(T x); T Pop(); ostream& Pop_Print(ostream& s); };

C++ 31 The Push Member Function template void MyStack ::Push(T x) { if ( n == I ) throw FullStack(); t[n++] = x; }

C++ 32 The Pop Member Function template T MyStack ::Pop() { if ( n == 0 ) throw EmptyStack(); return t[--n]; }

C++ 33 The Pop_Print Member Function template ostream& MyStack ::Pop_Print (ostream& s) { while(n > 0) s << t[--n] << " "; return s << endl; }

C++ 34 The Inserter Operator template ostream& operator & v) { return v.Pop_Print(s); }

C++ 35 The first main function (10 elements of type int) int main() { const int dim = 10; MyStack v; for(int i = 0; i < dim; i++) v.Push(i); cout << v; } Output:

C++ 36 The second main function (5 elements of type double) int main() { const int dimension = 5; MyStack v2; for(int i = 0; i < dimension; i++) v2.Push(i + static_cast (i) / 10); cout << v2; } Output:

C++ 37 The third main function (full stack) int main() { const int dim = 10; MyStack v; try { for(int i = 0; i <= dim; i++) v.Push(i); } catch( MyStack ::FullStack ) { cout << "The stack is full.\n"; } The stack is full. Output:

C++ 38 The last main function (empty stack) int main() { const int dim = 10; MyStack v; for(int i = 0; i < dim; i++) v.Push(i); try { while( true)cout << v.Pop() << " "; } catch( MyStack ::EmptyStack ) { cout << "Empty.\n"; } Empty. Output: