1 Lecture 8: Introduction to C++ Templates and Exceptions  C++ Function Templates  C++ Class Templates.

Slides:



Advertisements
Similar presentations
Alan YorinksLecture 7 1 • Tonight we will look at:: • List ADT • Unsorted List • Sequential Search • Selection Sort • Sorted List • Binary Search.
Advertisements

Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Lecture 18: 4/11/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
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,
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Templates Overload function: define more than one function With same function name Different parameter type Different type Different number of parameter.
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.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
Templates and the STL.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Data Structures Lecture-12 : STL Azhar Maqsood NUST Institute of Information Technology (NIIT)
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.
Containers Overview and Class Vector
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
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.
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 =
1 Chapter 17-1 Templates and Exceptions Dale/Weems.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
Copyright 2006, The Ohio State University Introduction to C++ Templates l C++ Function Templates l C++ Class Templates.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
1 Chapter 17 Templates and Exceptions Dale/Weems.
1 Chapter 17 Templates and Exceptions Dale/Weems/Headington.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
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.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
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.
Motivation for Generic Programming in C++
C++ Templates.
Chapter 18 Introduction to Custom Templates
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Generic programming – Function template
ADT Implementations: Templates and Standard Containers
Introduction to Programming
CMSC 202 Lesson 22 Templates I.
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.
Chapter 16 Linked Structures
Lists - I The List ADT.
Lists - I The List ADT.
Characteristics of OOPL Templates Standard Template Library
Templates I CMSC 202.
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.
Lecture 8: Introduction to C++ Templates and Exceptions
Chapter 3 Lists, Stacks, and Queues
More C++ Concepts Exception Handling Templates.
Presentation transcript:

1 Lecture 8: Introduction to C++ Templates and Exceptions  C++ Function Templates  C++ Class Templates

2 C++ Function Templates  Approaches for functions that implement identical tasks for different data types Naïve Approach Function Overloading Function Template  Instantiating a Function Templates

3 Approach 1: Naïve Approach  Create unique functions with unique names for each combination of data types Difficult to keep track of multiple function names lead to programming errors

Example void PrintInt( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void PrintChar( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void PrintFloat( float x ) { … } void PrintDouble( double d ) { … } PrintInt(sum); PrintChar(initial); PrintFloat(angle); To output the traced values, we insert:

5 Approach 2: Function Overloading – Review  The use of the same name for different C++ functions, distinguished from each other by their parameter lists  Eliminates the need to come up with many different names for identical tasks.  Reduces the chance of unexpected results caused by using the wrong function name.

Example of Function Overloading void Print( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void Print( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void Print( float x ) { } Print(someInt); Print(someChar); Print(someFloat); To output the traced values, we insert:

7 Approach 3: Function Template  A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types. Template FunctionDefinition FunctionTemplate TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier

Example of a Function Template template void Print( SomeType val ) { cout << "***Debug" << endl; cout << "Value is " << val << endl; } Print (sum); Print (initial); Print (angle); To output the traced values, we insert: Template parameter (class, user defined type, built-in types) Template argument

9 Instantiating a Function Template  When the compiler instantiates a template, it substitutes the template argument for the template parameter throughout the function template. Function (FunctionArgList) TemplateFunction Call

A more complex example template void sort(vector & v) { const size_t n = v.size(); for (int gap=n/2; 0<gap; gap/=2) for (int i=gap; i<n; i++) for (int j=i-gap; 0<j; j-=gap) if (v[j+gap]<v[j]) { T temp = v[j]; v[j] = v[j+gap]; v[j+gap] = temp; }

Summary of Three Approaches Naïve Approach Different Function Definitions Different Function Names Function Overloading Different Function Definitions Same Function Name Template Functions One Function Definition (a function template) Compiler Generates Individual Functions

12 Class Template  A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types. Template ClassDefinition Class Template TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier

Example of a Class Template template class GList { public: bool IsEmpty() const; bool IsFull() const; int Length() const; void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; void SelSort(); void Print() const; GList(); // Constructor private: int length; ItemType data[MAX_LENGTH]; }; Template parameter

14 Instantiating a Class Template  Class template arguments must be explicit.  The compiler generates distinct class types called template classes or generated classes.  When instantiating a template, a compiler substitutes the template argument for the template parameter throughout the class template.

Instantiating a Class Template // Client code GList list1; GList list2; GList list3; list1.Insert(356); list2.Insert(84.375); list3.Insert("Muffler bolt"); To create lists of different data types GList_int list1; GList_float list2; GList_string list3; template argument Compiler generates 3 distinct class types

16 Substitution Example class GList_int { public: void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; private: int length; ItemType data[MAX_LENGTH]; }; int

17 Function Definitions for Members of a Template Class template void GList ::Insert( /* in */ ItemType item ) { data[length] = item; length++; } //after substitution of float void GList ::Insert( /* in */ float item ) { data[length] = item; length++; }

18 Another Template Example: passing two parameters template class Stack {... T buf[size]; }; Stack mystack; non-type parameter

Standard Template Library  In the late 70s Alexander Stepanov first observed that some algorithms do not depend on some particular implementation of a data structure but only on a few fundamental semantic properties of the structure  Developed by Stepanov and Lee at HP labs in 1992  Become part of the C++ Standard in

20 What’s in STL  Container classes: vector, list, deque, set, map, and etc…  A large collection of algorithms, such as reverse, swap, heap, and etc.

21 Vector  A sequence that supports random access to elements Elements can be inserted and removed at the beginning, the end and the middle Constant time random access Commonly used operations  begin(), end(), size(), [], push_back(…), pop_back(), insert(…), empty()

Example of vectors // Instantiate a vector vector V; // Insert elements V.push_back(2);// v[0] == 2 V.insert(V.begin(), 3);// V[0] == 3, V[1] == 2 // Random access V[0] = 5;// V[0] == 5 // Test the size int size = V.size();// size == 2

23 Take Home Message  Templates are mechanisms for generating functions and classes on type parameters. We can design a single class or function that operates on data of many types Function templates Class templates