Templates 12/11/2018. Redundancy. Redundancy

Similar documents
Insertion sort 20/11/2018. The idea. Example

Selection sort 20/11/2018. The idea. Example

Console input 26/09/2018. Background. Background

Member functions 21/11/2018. Accessing member variables. Accessing member variables

Pointer arithmetic 20/11/2018. Pointer arithmetic. Pointer arithmetic

Linked Lists 28/11/2018. Nodes with member functions. The need for a linked list class

Pushing at the back 28/11/2018. Problem. Our linked list class

Throwing exceptions 02/12/2018. Throwing objects. Exceptions

Logical operators 20/09/2018. The unit pulse. Background

The structured programming theorem

Polymorphism 02/12/2018. Member functions. Member functions

Anatomy of a program 06/09/2018. Pre-processor directives. In this presentation, we will: Define the components of a program

The call stack and recursion and parameters revisited

Integer primitive data types

Main memory 05/10/2018. Main memory. Main memory

Dynamic memory allocation

Binary and hexadecimal numbers

Strings 20/11/2018. a.k.a. character arrays. Strings. Strings

Part XI. Algorithms and Templates. Philip Blakely (LSC) C++ Introduction 314 / 370

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

C++ Templates. David Camp

Assignment #1 Advanced Programming in C /2018. NPRG051 Advanced programming in C++ - Assignment #1

CS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p.

by Pearson Education, Inc. All Rights Reserved. 2

Object-Oriented Programming for Scientific Computing

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

Rvalue References & Move Semantics

CSCI-1200 Data Structures Fall 2017 Test 3 Solutions

Suppose that you want to use two libraries with a bunch of useful classes and functions, but some names collide:

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination T09:00

Exceptions. CandC++ 7. Exceptions Templates. Throwing exceptions. Conveying information

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 7. Exceptions Templates 2/1. Throwing exceptions 14 }

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

More on Templates. Shahram Rahatlou. Corso di Programmazione++

Part X. Advanced C ++

Templates. Zoltán Porkoláb: C++11/14 1

Variadic functions: Variadic templates or initializer lists? -- Revision 1

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

COEN244: Class & function templates

Outline. 1 About the course

Introduction to Programming

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

C and C++ 7. Exceptions Templates. Alan Mycroft

Introduction to C++ with content from

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Exercise 7 References, Arrays, Vectors

Default arguments, documentation

MIDTERM EXAMINATION Douglas Wilhelm Harder EIT 4018 x T09:30:00P1H20M Rooms: RCH-103 and RCH-302

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:30-7:00

Figure 1. A breadth-first traversal.

Templating functions. Comp Sci 1570 Introduction to C++ Administrative notes. Review. Templates. Compiler processing. Functions Overloading

Functions and Recursion

Comp151. Function Templates & Class Templates

Logistics. Templates. Plan for today. Logistics. A quick intro to Templates. A quick intro to Templates. Project. Questions? Introduction to Templates

Lesson 13 - Vectors Dynamic Data Storage

Debug C++ Without Running. Anastasia Kazakova

Introductory Project. ECE 250 Algorithms and Data Structures. Douglas Wilhelm Harder, M.Math. LEL Vajihollah Montaghami, M.A.Sc.

Types and Type Inference

ECE373 Abstraction, Methods, and Regions (and other things you didn t think you needed to know)

Function Templates. Consider the following function:

6.S096 Lecture 4 Style and Structure

CS-201 Introduction to Programming with Java

Inheritance and Overloading. Week 11

Writing Generic Functions. Lecture 20 Hartmut Kaiser hkaiser/fall_2013/csc1254.html

eingebetteter Systeme

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

Templates Templates are functions or classes that are parameterized. We have already seen a few in STL:

TEMPLATES AND ITERATORS

COMP6771 Advanced C++ Programming

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

15. Pointers, Algorithms, Iterators and Containers II

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

The paramaterless ctor (aka default ctor)

CS93SI Handout 04 Spring 2006 Apr Review Answers

Lectures 4 and 5 (Julian) Computer Programming: Skills & Concepts (INF-1-CP1) double; float; quadratic equations. Practical 1.

Goals of this Lecture

Exercise 1.1 Hello world

Allocation & Efficiency Generic Containers Notes on Assignment 5

Numerical computing. How computers store real numbers and the problems that result

CSCI-1200 Data Structures Fall 2018 Lecture 21 Hash Tables, part 1

C++ Templates. CSE 333 Autumn 2018

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

General Computer Science II Course: B International University Bremen Date: Dr. Jürgen Schönwälder Deadline:

Modern and Lucid C++ Advanced for Professional Programmers. Part 7 Compile-Time Computation. Department I - C Plus Plus

OPPA European Social Fund Prague & EU: We invest in your future.

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

C++14 Reflections Without Macros, Markup nor External Tooling

use static size for this buffer

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates

On the correctness of template metaprograms

Using Enum Structs as Bitfields

ECE 250 Data Structures and Algorithms MID-TERM EXAMINATION /5:30-7:00

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Transcription:

ECE 150 Fundamentals of Programming Outline 2 In this lesson, we will: Observe that much functionality does not depend on specific types See that normally different types require different function definitions Understand this is a serious waste of effort Introduce templates and their use Prof. Hiren Patel, Ph.D. Douglas Wilhelm Harder, M.Math. LEL hdpatel@uwaterloo.ca dwharder@uwaterloo.ca 2018 by Douglas Wilhelm Harder and Hiren Patel. Some rights reserved. 3 4 Suppose you author the function int max( int a, int b ); Next, you must author another function: double max( double a, double b ); int max( int a, int b ) { else { double max( double a, double b ) { else { 1

5 6 And another: long max( long a, long b ); And yet another: float max( float a, float b ); long max( long a, long b ) { else { float max( float a, float b ) { else { 7 8 All of these functions are identical with respect to functionality They only differ in the types of the parameters and the return type In each case, all these types are identical Would it not be nice to be able to write a function: typename max( typename a, typename b ); typename max( typename a, typename b ) { else { In this case, the compiler could determine the appropriate type This is, of course, possible, but it s a little bit more in-depth: T max( T a, T b ); else { 2

9 10 Think of T as a parameter to the function: For the function T max( T a, T b ); else { The compiler will now pick the appropriate variation: T max( T a, T b ); long a{5928395425359233, b{5928395425359234; double x{3.14, y{2.73; std::cout << max( a, b ) << std::endl; std::cout << max( x, y ) << std::endl; 11 12 The compiler, however, will not attempt to cast: long a{5928395425359233; double x{3.14; std::cout << max( a, x ) << std::endl; The compiler, however, will not attempt to cast: long a{5928395425359233; double x{3.14; std::cout << max<double>( a, x ) << std::endl; example.cpp: In function 'int main()': example.cpp:21:28: error: no matching function for call to 'max(long int&, double&)' std::cout << max( a, y ) << std::endl; example.cpp:21:28: note: candidate is: example.cpp:7:3: note: template<class T> T max(t, T) example.cpp: In function 'int main()': example.cpp:21:28: error: no matching function for call to 'max(long int&, double&)' std::cout << max( a, y ) << std::endl; example.cpp:21:28: note: candidate is: example.cpp:7:3: note: template<class T> T max(t, T) 3

13 Swapping variables 14 You can, if you wish, give the compiler a hint: long a{5928395425359233; double x{3.14; std::cout << max<double>( a, x ) << std::endl; 5.9284e+15 Consider this function: void swap( int &a, int &b ); void swap( int &a, int &b ) { int tmp{a; a = b; b = tmp; Again, the functionality does not depend on the fact the arguments are of type int Swapping variables 15 Finding the maximum array entry 16 Thus, we can factor out the type: void swap( T &a, T &b ); void swap( T &a, T &b ) { T tmp{a; a = b; b = tmp; Note that tmp is a local variable of the same type T Again, here is another function we saw: double array_max( double const array[], std::size_t const capacity, std::size_t &location ) { double max{array[0]; location = 0; for ( std::size_t k{1; k < capacity; ++k ) { if ( array[k] > max ) { max = array[k]; location = k; return max; 4

Finding the maximum array entry 17 18 Again, here is another function we saw: T array_max( T const array[], std::size_t const capacity, std::size_t &location ) { T max{array[0]; location = 0; for ( std::size_t k{1; k < capacity; ++k ) { if ( array[k] > max ) { max = array[k]; location = k; Note that max is a local variable of the same type T Many of these common functions already appear in the Standard Template Library (STL) Function Library std::swap #include <utility> std::max std::min Many of the algorithms we will cover in this course are implemented some way or another in the STL return max; 19 20 Other useful functions include std::count int array[10]{1, 5, 5, 2, 4, 7, 6, 2, 4, 5; for ( int k{0; k < 10; ++k ) { std::cout << k << ": " << std::count( array, array + 10, k ) << std::endl; 0: 0 1: 1 2: 2 3: 0 4: 2 5: 3 6: 1 7: 1 8: 0 9: 0 Pointer arithmetic! The address of the first entry The address one beyond the last entry Other useful functions include std::find int array[10]{1, 5, 5, 2, 4, 7, 6, 2, 4, 5; for ( int k{0; k < 10; ++k ) { int *p_loc = std::find( array, array + 10, k ); 1: array[0] == 1 2: array[3] == 2 4: array[4] == 4 5: array[1] == 5 6: array[6] == 6 7: array[5] == 7 if ( p_loc!= array + 10 ) { std::cout << k << ": array[" << (p_loc - array) << "] == " << *p_loc << std::endl; Pointer difference! The number of positions between the two addresses 5

21 22 Summary Finding the minimum and maximum entries int array[10]{3, 5, 5, 2, 4, 7, 6, 2, 4, 5; Minimum: array[3] == 2 Maximum: array[5] == 7 Following this lesson, you now Understand the benefits of templates Know that templates abstract out the type when the type is irrelevant to the operation Know how to define a function to use a template Understand that the Standard Template Library makes liberal use of templates for functions defined there int *p_min{ std::min_element( array, array + 10 ) ; int *p_max{ std::max_element( array, array + 10 ) ; std::cout << "Minimum: array[" << (p_min - array) << "] == " << *p_min << std::endl; std::cout << "Maximum: array[" << (p_max - array) << "] == " << *p_max << std::endl; Pointer difference! The number of positions between the two addresses 23 24 References Colophon [1] No references? These slides were prepared using the Georgia typeface. Mathematical equations use Times New Roman, and source code is presented using Consolas. The photographs of lilacs in bloom appearing on the title slide and accenting the top of each other slide were taken at the Royal Botanical Gardens on May 27, 2018 by Douglas Wilhelm Harder. Please see https://www.rbg.ca/ for more information. 6

Disclaimer 25 These slides are provided for the ECE 150 Fundamentals of Programming course taught at the University of Waterloo. The material in it reflects the authors best judgment in light of the information available to them at the time of preparation. Any reliance on these course slides by any party for any other purpose are the responsibility of such parties. The authors accept no responsibility for damages, if any, suffered by any party as a result of decisions made or actions based on these course slides for any other purpose than that for which it was intended. 7