Lecture 17 Templates, Part I. What is a Template? In short, it’s a way to define generic functionality on parameters without needing to declare their.

Slides:



Advertisements
Similar presentations
Template. 2 Using templates, it is possible to create generic functions and classes. In a generic function or class, the type of data upon which the function.
Advertisements

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.
TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
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.
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1 Random number generation Using srand(), rand() & time(0) Searching and Sorting Demo Making searching & sorting more generic Overloading the functions.
Lecture 18 Templates, Part II. From Last Time: What is a Template? This is the “official” specification for a template. It says that to define a template.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 5 Functions.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Bubble Sort Notes David Beard CS181. Bubble Sort for Strings Double pass algorithm to sort a single dimensional array. Inner loop “bubbles” largest element.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Algorithm Efficiency and Sorting
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
Templates & Generic Programming Junaed Sattar November 12, 2008 Lecture 10.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Java Generics.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
1 Chapter 17-1 Templates and Exceptions Dale/Weems.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
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.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
1 Using Templates COSC 1567 C++ Programming Lecture 10.
CS212: Object Oriented Analysis and Design
1 CSC241: Object Oriented Programming Lecture No 25.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Overview of C++ Templates
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
Lecture 14 Miscellaneous Topics II: Enuerations, Pointers to Functions (& Prelim Review)
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
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.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
1 FUNCTIONS - II Chapter 9 and Today we will continue with functions covering…. Passing by Reference  Scope Sorting variables Function Structure.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Templates Consider the following function, which swaps two integers: void swap(int &x, int &y) { int temp = x; x = y; y = temp; } int i = 3, j = 4; swap(i,
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
C++ Functions A bit of review (things we’ve covered so far)
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
C++ Templates.
FUNCTIONS In C++.
Chapter 14 Templates C++ How to Program, 8/e
Inheritance and Overloading
CS212: Object Oriented Analysis and Design
Templates.
Miscellaneous C++ Topics
Fundamental Programming
Miscellaneous Topics I
Lecture 3 More on Flow Control, More on Functions,
Presentation transcript:

Lecture 17 Templates, Part I

What is a Template? In short, it’s a way to define generic functionality on parameters without needing to declare their types. Consider the following example… Suppose you are in need of sorting arrays of various types. You may initially know that you only need to to sort integers, but what if you need to sort other types down the road? No matter what type(s) are involved, all sorting algorithms have a common need to swap (exchange) data elements in an array. We could abstractly represent this with the following pseudo- code: void swap( *a, int i, int j) { temp = a[i]; a[i] = a[j]; a[j] = temp; }

What is a Template? This pseudo-code gives us a “blueprint” for implementing the swap function for any given type. So, if I needed to sort arrays of integers, floating points and strings, I could provide three overloaded definitions of swap(). void swap(int *a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } void swap(float *a, int i, int j) { float temp = a[i]; a[i] = a[j]; a[j] = temp; }

What is a Template? With these three definitions of swap, I can happily write three sorting functions each dealing with one of the three types. Their prototypes might look like this: void swap(string *a, int i, int j) { string temp = a[i]; a[i] = a[j]; a[j] = temp; } // Sorting function prototypes... void sort(int *intArray, int size); void sort(float *floatArray, int size); void sort(string *stringArray, int size);

What is a Template? But wait… being big believers in choice and our natural tendencies to like to compare things… We want to have sorting routines for multiple sorting methods! We need more prototypes (well, and function definitions too!) // Insertion Sort function prototypes... void insertionSort(int *intArray, int size); void insertionSort(float *floatArray, int size); void insertionSort(string *stringArray, int size); // Bubble Sort function prototypes... void bubbleSort(int *intArray, int size); void bubbleSort(float *floatArray, int size); void bubbleSort(string *stringArray, int size); // Selection Sort function prototypes... void selectionSort(int *intArray, int size); void selectionSort(float *floatArray, int size); void selectionSort(string *stringArray, int size);

What is a Template? Uh oh, I just remembered. We can get a better range of numbers if we use doubles instead of floats, and in past semesters I’ve liked using MyString better than string. So... // swap function prototypes… void swap(int *a, int i, int j); void swap(float *a, int i, int j); void swap(string *a, int i, int j); void swap(double *a, int i, int j); void swap(MyString *a, int i, int j); // Insertion Sort function prototypes... void insertionSort(int *intArray, int size); void insertionSort(float *floatArray, int size); void insertionSort(string *stringArray, int size); void insertionSort(double *doubleArray, int size); void insertionSort(MyString *coolArray, int size);

What is a Template? Had enough yet? Let’s go back to our “blueprints” // Bubble Sort function prototypes... void bubbleSort(int *intArray, int size); void bubbleSort(float *floatArray, int size); void bubbleSort(string *stringArray, int size); void bubbleSort(double *doubleArray, int size); void bubbleSort(MyString *coolArray, int size); // Selection Sort function prototypes... void selectionSort(int *intArray, int size); void selectionSort(float *floatArray, int size); void selectionSort(string *stringArray, int size); void selectionSort(double *doubleArray, int size); void selectionSort(MyString *coolArray, int size);

Templates Defined I could also use the same abstraction to pseudo code to provide definitions for each of the sorting functions. In doing so I have (abstractly) defined the 20 functions I need for all of this sorting! void swap( *a, int i, int j) // pseudo code { temp = a[i]; a[i] = a[j]; a[j] = temp; } // Sorting function prototypes... void bubbleSort( *someArray, int size); void insertionSort( *someArray, int size); void selectionSort( *someArray, int size);

Templates Defined So how does all of this relate to templates? Well, the notion of abstracting out a function definition into pseudo code such that any type could be substituted is exactly what the concept of (function) templates is all about. If only the syntax were a little easier to look at! *sigh* Consider the following C++ function template definitions of swap() and sort(): template void swap(someType *a,int i,int j) { someType temp = a[i]; a[i] = a[j]; a[j] = temp; } template void insertionSort(aType *a,int size); template void bubbleSort(aType *a,int size); template void selectionSort(aType *a,int size);

What is a Template? This is the “official” specification for a template. It says that to define a template you must: start with the keyword template specify, in angle brackets, a placeholder name for each type you are using (these aren’t necessarily classes, that’s just the name chosen for this task) follow the angle brackets with your function name follow the function name with your parameter list (using any combination of real types and placeholder names) Again, the fact that you are using the keyword class for each placeholder you are defining has nothing to do with a C++ class. At compilation time the compiler will look at your code and generate a separate function for each type used throughout your code when calling template functions. template fn (formal args)

Calling Function Templates A function template is called just like any other function. There is an optional syntax for allowing the default “type resolution” to be overridden. Consider the following code: class Person { public: void whoAmI() { cout << “I am a Person!” << endl; } }; class Student : public Person { public: void whoAmI() { cout << “I am a student!” << endl; } }; template whoAmI(someone *x,Person *y) { x->whoAmI(); y->whoAmI(); }

Calling Function Templates In addition to calling whoAmI() like a normal function, I can also override the type of the argument being passed as the first parameter, like this: template whoAmI(someone *x,Person *y) { x->whoAmI(); y->whoAmI(); } int main() { Student alex; whoAmI(&alex,& alex); // Even though “alex” is a “Student”, treat like a “Person” whoAmI (&alex,&alex); }

Demonstration #1 Calling Function Templates

Overloading Operators with Templates We can take advantage of some existing global templates in the Standard Template Library to simplify INT. You see, operators can be overloaded with templates as well. The following templates exist in the Standard Template Library: template inline bool operator!=(const T& x,const T& y) { return !(x == y); } template inline bool operator>(const T& x,const T& y) { return (y < x); }

Overloading Operators with Templates If you’ll notice, this provides a definition for the operators !=, >, >= and <= in terms of == and <. This means that for any class you create that can be ordered, all you need to do is overload == and < and you’ll get all the comparison operators thanks to these templates. template inline bool operator<=(const T& x,const T& y) { return !(y < x); } template inline bool operator>=(const T& x,const T& y) { return !(x < y); }

Demonstration #2 Simplifying INT

Specialization Sometimes having a generic solution applied across all types doesn’t work the way you want it to. Consider the example of a template function used to do generic comparisons: It works fine for most types, but when we start using C style strings, it breaks down: // A generic template to compare two parameters of same type template bool isLessThan(aType arg1,aType arg2) { return arg1 < arg2; }

Specialization The problem is that our generic comparison routine will be comparing the pointer values for str1 and str2, not the strings they point at. If only we could make a special case… (can we?) int main() { int x = 7, y = 2; char *str1=“oregano”, *str2=“basil”; if (isLessThan(x,y)) // This is OK cout << “x less than y” << endl; if (isLessThan(str1,str2)) // Is this what we want? cout << “str1 less than str2” << endl; } bool isLessThan(char *str1,char *str2) { return (strcmp(str1,str2) < 0); }

Demonstration #3 Specialization

Lecture 17 Final Thoughts