CMSC 202 Templates.

Slides:



Advertisements
Similar presentations
Templates in C++. Generic Programming Programming/developing algorithms with the abstraction of types The uses of the abstract type define the necessary.
Advertisements

CS-1030 Dr. Mark L. Hornick 1 Constructors Copy Constructors.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
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,
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Intro to Generic Programming Templates and Vectors.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
1 COMS 261 Computer Science I Title: Classes Date: November 7, 2005 Lecture Number: 28.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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 =
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
ECE122 Feb. 22, Any question on Vehicle sample code?
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Templates L. Grewe. 2 Goals Often want to do basically the same thing w/diff things –functions work on variables only types specified –  algorithmic.
March 2006 Copyright, 2006 Oxford Consulting, Ltd C++ Templates Templates F Part of the ongoing development of the C++ language F Integral part.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
1 CSC241: Object Oriented Programming Lecture No 25.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
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.
Constructor It is a special member of a class that has the following characteristic 1)It has the same name as of its class. 2)It don’t have an explicit.
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)
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 2 Objects and Classes
C++ Template.
Pointer to an Object Can define a pointer to an object:
Topics: Templates Exceptions
Programming with ANSI C ++
Submission Example May 14, 2018
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Template Classes CMPS 2143.
Templates.
FUNCTIONS In C++.
Why exception handling in C++?
Functions Separate Compilation
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Lesson 14 Copy and Assignment
Templates.
The dirty secrets of objects
Templates in C++.
Chapter 2 Objects and Classes
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
CMSC 202 Lesson 22 Templates I.
Abstraction: Generic Programming, pt. 2
Polymorphism CMSC 202, Version 4/02.
C++ Templates CSE 333 Summer 2018
Templates I CMSC 202.
Java Programming Language
Really reusable software
CMSC 341 C++ and OOP.
CMSC 202 Lesson 6 Functions II.
Templates Generic Programming.
Templates An introduction.
CMSC 341 C++ and OOP.
Templates CMSC 202, Version 4/02.
Miscellaneous Topics I
Templates Generic Programming.
Copy Constructors and Overloaded Assignment
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

CMSC 202 Templates

A form of Polymorphism Provide “parametric polymorphism” Polymorphism: ability of variable/function/class to take more than one form ad-hoc polymorphism: function overloading true polymorphism: virtual member functions; dynamic binding parametric polymorphism: controlled through a parameter works at compile time Two types function templates class templates

Why Function Templates? Suppose you want to write a function with two args of same type which returns the largest. Could overload the function for each data type int maxInt (int a, int b); int maxFloat (float a, float b); … Foo maxFoo(const Foo& a, const Foo& b);

Why Function Templates? (2) The code in each would look the same if (a < b) return b; else return a; The algorithm does not rely on the data type.

Write one to fit (almost) all Using templates, we can write one function to handle (almost) all data types and classes template <class T> T& max (const T& a, const T& b) { if ( a < b) return b; else return a; } T is called the “template type parameter” and can have any name.

The compiler creates code When compiler sees this code int i1 = 1, i2 = 2, i3; i3 = max(i1, i2); It creates this function int& max (const int& a, const int& b) { if (a < b) return b; else return a; }

max( ) for floats When compiler sees this code float f1 = 1.2 f2 = 2.2, f3; f3 = max(f1, f2); It creates this function float& max (const float& a, const float& b) { if (a < b) return b; else return a; }

max( ) for Foo When compiler sees this code It creates this function Foo F1 = value1, F2 = value2, F3; F3 = max(F1, F2); It creates this function Foo& max (const Foo& a, const Foo& b) { if (a < b) return b; else return a; }

Calling a template function Note that the function call to max( ) was not changed i3 = max (i1, i2); f3 = max (f1, f3); etc. The caller doesn’t “know” it’s a template function

Can max( ) be created for any class? Answer -- Almost Note that max ( ) includes the statement if ( a < b ) ….. What does this imply about any class for which the compiler wishes to create max ()? Answer – that class must support operator<

A special case Suppose you write the following: char *str1 = “abc”; char *str2 = “def”; cout << max(str1, str2) << endl;

max( ) for char * When the compiler sees this code char *str1 = “abc”; char *str2 = “def”; cout << max(str1, str2) << endl; It creates this function char*& max (char*& a, char*& b) { if (a < b) return b; else return a; } What gets compared?

What gets compared? Unfortuately, the addresses (pointers) are compared, not contents. This is almost assuredly NOT what you want. Can work around this problem by overloading max() and providing an explicit function for char * char* max(char *a, char *b) { if (strcmp(a,b) < 0) return b; else return a; } The compiler will look for an exact function signature match before using the template

Class templates Templates can be provided for classes as well as functions This is how we create generic classes that work with all data types Also the basis for “container” classes that provide the structure for efficiently accessing data regardless of its type

smartArray of ints revisited class smartArray { public: smartArray ( int size = 100 ); // other members private: int _size; int *_theData; // this is what makes it // a smartArray of ints };

Nothing special about a smartArray of ints Nothing in the code for the smartArray relies on the fact that this is an array of ints. We can create a class template for smartArray so that we use it for any primitive data type or class assuming…. ….that the class has the necessary overloaded operators

smartArray template template <class T> class smartArray { public: smartArray ( int size = 100 ); // other members private: int _size; // this really is an int T *_theData; // the array of any type };

Default constructor for smartArray class template // Each member function is a function template template <class T> smartArray<T>::smartArray (int size) { _size = size; _theData = new T [_size]; // an array of Ts for (int j = 0; j < _size; j++) // just to be nice _theData [ j ] = T( ); // default object }

Copy constructor for smartArray class template template <class T> smartArray<T>::smartArray (const smartArray<T>& a) { _size = a._size; _theData = new T [ _size ]; for (int j = 0; j < _size; j++ ) _theData[ j ] = a._theData [ j ]; }

Another example - operator [ ] template <class T> T smartArray<T>::operator[ ] (int index) { return _theData [ index ] ; }

Template .H and .C files As usual, we put the class template in the .H file and the implementation in the .C file Same for function templates

Using smartArray In our main program #include “smartArray.H” Define some smartArrays smartArray<float> array1; smartArray<myClass> array2; When the compiler sees these definitions, it looks for the smartArray template to determine how to generate the code, then compiles it

How does the compiler “find” the implementation (.C) file This varies from compiler to compiler Some compilers assume that the code for the template found in xyzzy.H will be in xyzzy.C -- they assume the same “root” filename The g++ compiler isn’t that smart

Templates and g++ This applies ONLY to templates For the g++ compiler to find the implementation of a template, we must #include the .C file inside the .H file Also note that this means you DO NOT #include the .H file inside the .C file as you normally would This applies ONLY to templates

smartArray.H #ifndef __SMARTARRAY__ #define __SMARTARRAY__ template <class T> class smartArray { public: smartArray ( int size = 100 ); // other members private: int _size; T *_theData; // the array of any type }; #include “smartArray.C” // include the implementation #endif

Compiling templates Function and class templates are just that – templates (I.e. frameworks) that tell the compiler how to generate code. The compiler can’t generate any meaningful code until it knows what type to use in place of the template type parameter. So compiling max.C (smartArray.C) will never create a meaningful max.o (smartArray.o), so we don’t include rules for making max.o in our makefile. The code will get generated and compiled when we use the template.

More about compiling We can compile max.C (smartArray.C) to check for syntax errors (using the -c switch), but this is done manually and carefully. We just said that with g++, we #include max.C inside max.H… then what happens if we compile max.C?? Since we don’t include max.H in max.C, we can expect to get errors when compiling max.C. If we really want to do this, we must temporarily do the normal thing – include the .H in the .C, but don’t include the .C in the .H

Writing templates Often the best way is to write your function, or design your class to work just with ints. Then, replace all the appropriate ints (not ALL the ints) with the template type parameter