Templates I CMSC 202.

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

1 Data Structures - CSCI 102 CS102 C++ Operator Overloading Prof Tejada.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
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,
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CS Oct 2006 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
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.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 28P. 1Winter Quarter Inheritance and Overloading.
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.
Intro to Generic Programming Templates and Vectors.
CMSC 202 Lesson 12 Operator Overloading II. Warmup  Overload the + operator to add a Passenger to a Car: class Car { public: // some methods private:
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
CMSC 202 Lesson 19 Polymorphism 2. Warmup What is wrong with the following code? What error will it produce? (Hint: it already compiles) for (unsigned.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
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 =
Object-Oriented Programming in C++
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
Computer Programming & Applications Mohamed Iqbal Pallipurath Lecture 02P. 1 Inheritance and Overloading Lecture 28.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
1 CSC241: Object Oriented Programming Lecture No 25.
Overview of C++ Templates
Chapter 3 Templates Saurav Karmakar Spring Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
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.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
CMSC 341 Lecture 2. Announcements Tutors wanted Office hrs Project 1.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
CMSC 202 Lesson 26 Miscellaneous Topics. Warmup Decide which of the following are legal statements: int a = 7; const int b = 6; int * const p1 = & a;
MAITRAYEE MUKERJI Object Oriented Programming in C++
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Motivation for Generic Programming in C++
Topics: Templates Exceptions
Programming with ANSI C ++
C++ Templates.
Template Classes CMPS 2143.
Templates.
FUNCTIONS In C++.
Exceptions, Templates, and the Standard Template Library (STL)
Object-Oriented Programming (OOP) Lecture No. 21
Function Overloading.
OOP-4-Templates, ListType
Templates.
CMSC 202 Lesson 21 Exceptions II.
CMSC 341 Lecture 6 – Templates
CMSC 202 Templates.
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Templaets It is a new concept which enables us to define “generic class “ and “generic function” to provide the “ generic programming” We are familiar.
Introduction to Programming
CMSC 202 Lesson 22 Templates I.
Abstraction: Generic Programming, pt. 2
Functions 2: Stupid Function Tricks
Exception Handling.
7 Arrays.
CMSC 202 Lesson 6 Functions II.
C++ Templates An Introduction to Generic Programming.
Templates An introduction.
Function Templates Class Templates
PROGRAMMING IN HASKELL
Templates CMSC 202, Version 4/02.
COP 3330 Object-oriented Programming in C++
Presentation transcript:

Templates I CMSC 202

Warmup Define a class that represents an index out of bounds exception Your class should have: Data member that is the index requested Data member that is the function name that throws the exception Data member that is the vector/array that the index was out of bounds on

Recall… Polymorphism Types seen so far? What’s left? “Many shapes” Ad-hoc Functional overloading Dynamic (true) Virtual member functions, dynamic binding What’s left? Parameterized Parameter-based (type based), static binding Function & class-based templates

Problem? Common algorithms/actions for all/many types Swap findMax/Min/Worst/Better Sort search

We want to reuse this code for ALL types! Imagine… float max ( const float a, const float b ); int max ( const int a, const int b ); Rational max ( const Rational& a, const Rational& b); myType max ( const myType& a, const myType& b); Code for each looks the same… if ( a < b ) return b; else return a; We want to reuse this code for ALL types!

T can be any identifier you want Templates Fundamental idea Write one implementation Use for any type Compiler generates appropriate code Syntax template <class T> retType funcName ( …, T varName, … ) { // some code… } Important! Wherever you would usually use the type of the templating object, you use T instead! T can be any identifier you want

Notice how ‘T’ is mapped to ‘int’ everywhere in the function… Template Example Function Template template <class T> T max ( const T& a, const T& b) { if ( a < b ) return b; else return a; } Compiler generates code based on the argument type cout << max(4, 7) << endl; Generates the following: int max ( const int& a, const int& b) Notice how ‘T’ is mapped to ‘int’ everywhere in the function…

A Closer Look… Function Template template <class T> T max ( const T& a, const T& b) { if ( a < b ) return b; else return a; } Notice Types that you want to use with this function must support the operator< Compiler will give you an error if this operator is not supported

New variables of type T? Let’s think about Swap() There is a templated swap() already defined for your use… What might it look like? template <class T> void Swap ( T& a, T& b) { T temp; temp = a; a = b; b = temp; } Assuming the code: double x = 7.0; double y = 5.4; Swap(x, y); Compiler generates: void Swap (double & a, double & b) { double temp; temp = a; a = b; b = temp; }

What’s wrong here? Assume the code: template <class T> T max ( const T& a, const T& b) { if ( a < b ) return b; else return a; } Assume the code: char* s1 = “hello”; char* s2 = “goodbye”; cout << max( s1, s2 ); Compiler generates: char* max ( const char*& a, const char*& b) { if ( a < b ) return b; else return a; } Is this what we want?

How can we fix this? Create an explicit version of max to handle char*’s Compiler will match this version and not use the template… char* max(char *a, char *b) { if (strcmp(a,b) < 0) return b; else return a; }

Compiling Templates First trick… As you create templated functions… Since compiler generates code based on function call… If you don’t actually CALL a templated function, it MIGHT not get compiled! Or it might only get a general syntax check without strong type-checking… As you create templated functions… Create a “dummy” main to call the function Similarly with templated classes…

Practice Implement a templated function that Searches a vector of some type Finds the minimum element You may assume the operator< is defined Returns that element

Challenge Create a templated function Sorts a vector of a templated type Use any style of sort you like Quicksort Linear Insertion Merge Bubble Assume that operator> and operator< are overloaded (so that you can use either…) Try and do it in the fewest lines of code!