CIS 190: C/C++ Programming. Lecture 13 Templates

Similar documents
Object Oriented Software Design II

An Incomplete C++ Primer. University of Wyoming MA 5310

Conversion Constructors

C++ INTERVIEW QUESTIONS

The C Programming Language course syllabus associate level

C++ Overloading, Constructors, Assignment operator

C++ Programming Language

J a v a Quiz (Unit 3, Test 0 Practice)

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Sources: On the Web: Slides will be available on:

6.s096. Introduction to C and C++

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

One positive experience I've had in the last 24 hours: Exercise today:

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Project 2: Bejeweled

1 Abstract Data Types Information Hiding

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

CISC 181 Project 3 Designing Classes for Bank Accounts

Tutorial on C Language Programming

Introduction to Data Structures

Comp151. Definitions & Declarations

Lecture 5: Java Fundamentals III

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

csce4313 Programming Languages Scanner (pass/fail)

OpenCL Static C++ Kernel Language Extension

13 Classes & Objects with Constructors/Destructors

Chapter 5 Functions. Introducing Functions

Introduction to Scientific Computing Part II: C and C++ C. David Sherrill School of Chemistry and Biochemistry Georgia Institute of Technology

The programming language C. sws1 1

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Pemrograman Dasar. Basic Elements Of Java

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

El Dorado Union High School District Educational Services

C++FA 5.1 PRACTICE MID-TERM EXAM

Interface Definition Language

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

CIS 190: C/C++ Programming. Polymorphism

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

arrays C Programming Language - Arrays

Computer Programming C++ Classes and Objects 15 th Lecture

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

Beyond the Mouse A Short Course on Programming

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Variable Base Interface

Introduction to Python

LAB4 Making Classes and Objects

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Description of Class Mutation Mutation Operators for Java

Java Crash Course Part I

Programming Languages CIS 443

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Introduction to Python

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

How To Program In Scheme (Prolog)

Semantic Analysis: Types and Type Checking

Dice. David Watkins Emily Chen Khaled Atef Phillip Schiffrin. djw2146 ec2805 kaa2168 pjs2186. Manager System Architect Testing Language Guru

CmpSci 187: Programming with Data Structures Spring 2015

Programming Database lectures for mathema

Semantic Checker (Part I)

Crash Course in Java

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

Java from a C perspective. Plan

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

6.S096 Lecture 1 Introduction to C

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Why you shouldn't use set (and what you should use instead) Matt Austern

Java Interview Questions and Answers

Binary storage of graphs and related data

Introduction to Python

SQL Server Array Library László Dobos, Alexander S. Szalay

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Class 16: Function Parameters and Polymorphism

Example of a Java program

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

A Grammar for the C- Programming Language (Version S16) March 12, 2016

Introduction to Java

The Payroll Program. Payroll

Ada-95 dla programistów C/C++

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Transcription:

CIS 190: C/C++ Programming Lecture 13 Templates

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 2

Overloading used to create multiple definitions for functions in various settings: constructors (in a class) operators (in a class) functions let s look at a simple swap function 3

Swap Function this is a function to swap two integers: void SwapVals(int &v1, int &v2) { int temp; } temp = v1; v1 = v2; v2 = temp; 4

Swap Function this is a function to swap two integers: void SwapVals(int &v1, int &v2) { int temp; } temp = v1; v1 = v2; v2 = temp; what if we want to swap two floats? 5

Swap Function this is a function to swap two floats: void SwapVals(float &v1, float &v2) { float temp; } temp = v1; v1 = v2; v2 = temp; 6

Swap Function this is a function to swap two floats: void SwapVals(float &v1, float &v2) { float temp; } temp = v1; v1 = v2; v2 = temp; what if we want to swap two chars? 7

Swap Function this is a function to swap two chars: void SwapVals(char &v1, char &v2) { char temp; } temp = v1; v1 = v2; v2 = temp; 8

Swap Function this is a function to swap two chars: void SwapVals(char &v1, char &v2) { char temp; } temp = v1; v1 = v2; v2 = temp; what if we want to swap two strings? 9

Swap Function okay, this is getting ridiculous 10

Swap Function okay, this is getting ridiculous should be able to write just one function that can handle all of these things and it is! using templates 11

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 12

What Are Templates? templates let us create functions and classes that can use generic input and types this means that functions like SwapVals() only need to be written once and then it can be used for almost anything 13

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> 14

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> this keyword tells the compiler that what follows this will be a template 15

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> this does not mean class in the same sense as C++ classes with members! 16

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> this does not mean class in the same sense as C++ classes with members! in fact, the (more) correct keyword to use is actually typename, because we are defining a new type 17

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> this does not mean class in the same sense as C++ classes with members! in fact, the (more) correct keyword to use is actually typename, because we are defining a new type but class is more common by far, and so we will use class to avoid confusion 18

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> T is the name of our new type 19

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> T is the name of our new type we can call it anything we want, but using T is the traditional way 20

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> T is the name of our new type we can call it anything we want, but using T is the traditional way (of course, we can t use int or for or any other types or keywords as a name for our type) 21

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> what this line means overall is that we plan to use T in place of types (int, char, etc.) 22

Indicating Templates to let the compiler know you are going to apply a template, use the following: template <class T> what this line means overall is that we plan to use T in place of types (int, char, etc.) this template prefix needs to be used before both function declarations and definitions 23

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 24

Using Templates template <class T> in order to create a function that uses templates, we first prefix it with this 25

Using Templates template <class T> void SwapVals(T &v1, T &v2) { } next, we use T in place of the types that we want to be generic for our function 26

Using Templates template <class T> void SwapVals(T &v1, T &v2) { T temp; } if we need these generic types inside our function, we declare them as being type T 27

Using Templates template <class T> void SwapVals(T &v1, T &v2) { T temp; temp = v1; v1 = v2; v2 = temp; } everything else about our function can remain the same 28

Using Templates when we call these templated functions, nothing looks different: SwapVals(intOne, inttwo); SwapVals(charOne, chartwo); SwapVals(strOne, strtwo); 29

(In)valid Use of Templates which of the following will work? SwapVals(int, int); SwapVals(char, string); SwapVals(TRAIN_CAR, TRAIN_CAR); SwapVals(double, float); SwapVals(Shape, Shape); SwapVals( hello, world ); 30

(In)valid Use of Templates templated functions can handle any input types that makes sense i.e., any type where the behavior that occurs in the function is defined even user-defined types! as long as the behavior is defined 31

Question from Class Q: What will happen if we overload SwapVals() manually for a specific type (like int)? A: The compiler accepts it, and a call to SwapVals() with integers will default to our manual overload of the function. It makes sense that if an int version of SwapVals() exists, the compiler will not create one of its own. 32

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 33

Compiler Handling the compiler can create code to handle any (valid) call of SwapVals() we can create it creates separate (overloaded) functions called SwapVals() that take in ints, or chars, or floats, or TRAIN_CAR structs, or anything else that we could give 34

Compiler Handling exactly what versions of SwapVals() are created is determined at time 35

Compiler Handling exactly what versions of SwapVals() are created is determined at compile time if we call SwapVals() with integers and strings, the compiler will create versions of the function that take in integers and strings 36

Separate Compilation which versions of templated function to create are determined at compile time how does this affect our use of separate compilation? function declaration in.h file function definition in.cpp file function call in separate.cpp file 37

Separate Compilation here s an illustrative example: #include swap.h int main() { int a = 3, b = 8; SwapVals(a, b); } main.cpp template <class T> void SwapVals(T &v1, T &v2); swap.h #include swap.h template <class T> void SwapVals(T &v1, T &v2) { T temp; temp = v1; v1 = v2; v2 = temp; } swap.cpp 38

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when swap.cpp is compiled 39

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when swap.cpp is compiled there are no calls to SwapVals() 40

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when swap.cpp is compiled there are no calls to SwapVals() swap.o has no SwapVals() definitions made 41

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when main.cpp is compiled 42

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when main.cpp is compiled it assumes everything is fine since swap.h has the appropriate declaration 43

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when main.o and swap.o are linked 44

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when main.o and swap.o are linked everything goes wrong 45

Separate Compilation most compilers (including eniac s) cannot handle separate compilation with templates when main.o and swap.o are linked everything goes wrong error: undefined reference to void SwapVals<int>(int&, int&) 46

Solutions the template function definition code must be in the same file as the function call code two ways to do this: place function definition in main.c place function definition in swap.h, which is #included in main.c 47

Solutions second option keeps some sense of separate compilation, and better allows code reuse #include swap.h int main() { int a = 3, b = 8; SwapVals(a, b); } main.cpp // declaration template <class T> void SwapVals(T &v1, T &v2); // definition template <class T> void SwapVals(T &v1, T &v2) { T temp; temp = v1; v1 = v2; v2 = temp; } swap.h 48

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 49

Class Templates syntax for class declaration is very similar: template <class T> class Pair { private: T GetFirst(); void SetFirst(T first); private: T m_first; T m_second; }; 50

Class Templates syntax for class declaration is very similar: template <class T> class Pair { private: T GetFirst(); void SetFirst(T first); private: T m_first; T m_second; }; 51

Class Templates syntax for class declaration is very similar: template <class T> class Pair { private: T GetFirst(); void SetFirst(T first); private: T m_first; T m_second; }; 52

Class Templates syntax for class declaration is very similar: template <class T> class Pair { private: T GetFirst(); void SetFirst(T first); private: T m_first; T m_second; }; 53

Templated Classes most common use for templated classes is containers (like our Pair example) in fact, many of the C++ STL containers actually use templates behind the scenes! like vectors! 54

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 55

Class Constructors normally, we create just one constructor, by using default parameters: Date (int m = 10, int d = 15, int y = 2014); this allows us to create a Date object with no arguments, all arguments, and everything in between 56

Templated Class Constructors can we do the same with our Pair class? 57

Templated Class Constructors can we do the same with our Pair class? Pair (T first = 0, T second = 0); 58

Templated Class Constructors can we do the same with our Pair class? Pair (T first = 0, T second = 0); this works fine if we re creating a Pair object of a number type (int, float, double), but what about strings, or TRAIN_CAR? 59

Templated Class Constructors can we do the same with our Pair class? Pair (T first = 0, T second = 0); this works fine if we re creating a Pair object of a number type (int, float, double), but what about strings, or TRAIN_CAR? the nature of templates means we can t use default parameters for templated classes 60

Templated Class Constructors need to create two constructors for the class??? and??? 61

Templated Class Constructors need to create two constructors for the class empty constructor (no arguments) Pair (); and??? 62

Templated Class Constructors need to create two constructors for the class empty constructor (no arguments) Pair (); and complete constructor (all arguments) Pair (T first, T second); 63

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 64

Templated Class Definitions just like with regular functions, member function definitions need the template prefix template <class T> 65

Templated Class Definitions just like with regular functions, member function definitions need the template prefix template <class T> in addition, they need a template indicator before the scope resolution operator: Pair<T>::Pair(T first, T second); 66

Templated Class Definitions just like with regular functions, member function definitions need the template prefix template <class T> in addition, they need a template indicator before the scope resolution operator: Pair<T>::Pair(T first, T second); note that the constructor name does not contain <T>, only the class name does 67

Templated Class Definitions everything else about the function behaves as with non-member templated functions Pair<T>::Pair(T first, T second) { } SetFirst(first); SetSecond(second); 68

Templated Class Definitions everything else about the function behaves as with non-member templated functions Pair<T>::Pair(T first, T second) { } m_first = first; m_second = second; since most error checking is not feasible with templated classes, it is fine to directly set variables in the constructor, as above 69

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 70

Using Templated Classes identical to the way you use templated classes provided by the STL (like vectors) 71

Using Templated Classes identical to the way you use templated classes provided by the STL (like vectors) vector <int> myvector(10); vector <char> avector; 72

Using Templated Classes identical to the way you use templated classes provided by the STL (like vectors) vector <int> myvector(10); vector <char> avector; Pair <string> hi( hello, world ); Pair <int> coordinates; 73

Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using Project 74

Project alpha due this Sunday (23rd) @ midnight presentation days will be Tuesday, Dec 2nd (6-7:30) and Wednesday, Dec 3rd (1:30-3) attendance at both presentation days is mandatory! you will lose points for skipping! final code turn-in is Wed, Dec 3rd @ midnight 75