1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
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.
CMSC 202, Version 2/02 1 Operator Overloading Strong Suggestion: Go over the Array class example in Section 8.8 of your text. (You may ignore the Array.
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,
Chapter 14: Overloading and Templates
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Templates CS-341 Dick Steflik. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply certain attributes.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Multiple-Subscripted Array
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Templates CS-240 Dick Steflik & DJ. Foreman. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
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 and the STL.
Templates CS212 & CS-240. Reuse Templates allow extending our classes Allows the user to supply certain attributes at compile time. Attributes specified.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
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.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures Course Review Midterm.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
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.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
1 Joe Meehean.  Suppose we wanted a class to store a pair of ints  Access the first using first()  and the second using second()  Lets call it LCPair.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
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:
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
1 Chapter 1 C++ Basics Review Reading: Sections 1.4 and 1.5.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
1 Chapter 1 C++ Templates Sections 1.6 and Templates Type-independent patterns that can work with multiple data types –Generic programming –Code.
Chapter 3 Templates Saurav Karmakar Spring Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates.
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
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.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 COMS 261 Computer Science I Title: Classes Date: November 9, 2005 Lecture Number: 29.
Chapter 1 C++ Templates (Sections 1.6, 1.7). Templates Type-independent patterns that can work with multiple data types. Function Templates  These define.
1 Introduction to Object Oriented Programming Chapter 10.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
1 Chapter (1) – Introduction Objectives Consistency and importance of the performance of a program for inputs of Different sizes. Basic mathematical background.
Chapter 2 Objects and Classes
Chapter 1 C++ Basics Review
Chapter 2 Objects and Classes
CMSC 341 C++ and OOP.
CMSC 341 C++ and OOP.
CMSC 341 C++ and OOP.
CMSC 341 C++ and OOP.
CMSC 341 C++ and OOP.
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Presentation transcript:

1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7

2 Templates Type-independent patterns that can work with multiple data types. –Generic programming –Code reusable Function Templates –These define logic behind the algorithms that work for multiple data types. Class Templates –These define generic class patterns into which specific data types can be plugged in to produce new classes.

3 Function Templates Example Generic function to find a maximum value in a given vector If argument is a vector type, then compiler generates a corresponding function –where Comparable is replaced by int type. Similarly for vector, vector etc. Assumption in this example: –Operator < is defined in the Comparable. Hence assumptions made by the template must be clearly stated. template

4 Function Templates Usage Each call to findMax() on a different data type forces the compiler to generate a different function using the template. Compiler will complain about findMax(v4) –because IntCell class does not defined operator<

class Square { public: explicit Square( double s = 0.0 ) : side{ s } { } double getSide( ) const { return side; } double getArea( ) const { return side * side; } double getPerimeter( ) const { return 4 * side; } void print( ostream & out = cout ) const { out << "(square " << getSide( ) << ")"; } bool operator< ( const Square & rhs ) const { return getSide( ) < rhs.getSide( ); } private: double side; }; // Define an output operator for Square ostream & operator<< ( ostream & out, const Square & rhs ) { rhs.print( out ); return out; } 5 An example Operator Overloading –Comparison operator< Defines the meaning of operator< for Employee class. –Output operator<< Define a global nonclass function operator<< that calls print(…) Define a public member function print( ostream & out)

template const Object & findMax( const vector & arr, Comparator cmp ) { int maxIndex = 0; for( int i = 1; i < arr.size( ); ++i ) if( cmp.isLessThan( arr[ maxIndex ], arr[ i ] ) ) maxIndex = i; return arr[ maxIndex ]; } class CaseInsensitiveCompare { public: bool isLessThan( const string & lhs, const string & rhs ) const { return strcasecmp( lhs.c_str( ), rhs.c_str( ) ) < 0; } }; int main( ) { vector arr = { "ZEBRA", "alligator", "crocodile" }; cout << findMax( arr, CaseInsensitiveCompare{ } ) << endl; return 0; } 6 Function Objects Objects whose primary purpose is to define a function Here findMax accepts a Comparator parameter as a function object. –Comparator assumed to define the isLessThan(…) function. There is a more formal way to define function objects in C++ (next slide).

template const Object & findMax( const vector & arr, Comparator isLessThan ) { int maxIndex = 0; for( int i = 1; i < arr.size( ); ++i ) if( isLessThan( arr[ maxIndex ], arr[ i ] ) ) maxIndex = i; return arr[ maxIndex ]; } const Object & findMax( const vector & arr ) { return findMax( arr, less { } ); } class CaseInsensitiveCompare { public: bool operator( )( const string & lhs, const string & rhs ) const { return strcasecmp( lhs.c_str( ), rhs.c_str( ) ) < 0; } }; int main( ) { vector arr = { "ZEBRA", "alligator", "crocodile" }; cout << findMax( arr, CaseInsensitiveCompare{ } ) << endl; cout << findMax( arr ) << endl; return 0; } 7 Function objects in C++ style Using operator overloading –Define operator () for CaseInsensitiveCompare class –Instead of cmp.operator()(x,y) we can use cmp(x,y) Case-sensitive comparison can also be performed using STL function object less (...)

/** * A class for simulating a memory cell. */ template class MemoryCell { public: explicit MemoryCell( const Object & initialValue = Object{ } ) : storedValue{ initialValue } { } const Object & read( ) const { return storedValue; } void write( const Object & x ) { storedValue = x; } private: Object storedValue; }; 8 Class Template Example MemoryCell template can be used for any type Object. Assumptions –Object has a zero parameter constructor –Object has a copy constructor –Copy-assignment operator Convention –Class templates declaration and implementation usually combined in a single file. –It is not easy to separate them in independent files due to complex c++ syntax. –This is different from the convention of separating class interface and implementation in different files.

Another Way (Implementation outside of declaration) 9 template class MemoryCell { public: explicit MemoryCell(const T& initialVale = T{}); const T& read() const; void write(const T& x); private: T storedValue; }; template MemoryCell ::MemoryCell(const T& initialValue): storedValue{initialValue} {} template const T& MemoryCell ::read() const { return storedValue; } template void MemoryCell ::write(const T& x) { storedValue = x; }

int main( ) { MemoryCell m1; MemoryCell m2{ "hello" }; m1.write( 37 ); m2.write( m2.read( ) + " world" ); cout << m1.read( ) << endl << m2.read( ) << endl; return 0; } 10 Class Template Usage Example MemoryCell can be used to store both primitive and class types. Remember –MemoryCell is not a class. –It’s a class template. –MemoryCell, MemoryCell etc are classes.

#include using namespace std; template class matrix { public: matrix( int rows, int cols ) : array( rows ) { for( auto & thisRow : array ) thisRow.resize( cols ); } matrix( const vector > & v ) : array{ v } { } matrix( vector > && v ) : array{ std::move( v ) } { } const vector & operator[]( int row ) const { return array[ row ]; } vector & operator[]( int row ) { return array[ row ]; } int numrows( ) const { return array.size( ); } int numcols( ) const { return numrows( ) ? array[ 0 ].size( ) : 0; } private: vector > array; // C++11 // vector > array; // prior to c++11 }; 11 Matrices C++ library does not provide a matrix class Constructor –Creates rows number of zero- sized vectors –Resizes each vector to col elements Two types of [] operators –One for LHS that returns by reference –Another for RHS that returns by constant reference –So we have two very identical functions What makes their signatures different?

12 Reading Assignment 2.1, 2.2, 2.3, 2.4.1, 2.4.2, 2.4.3