Templates CMSC 202, Version 4/02.

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

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.
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.
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.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
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 =
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
ECE122 Feb. 22, Any question on Vehicle sample code?
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
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.
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.
Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University 24/2/2014 Ebtsam Abdelhakam 1.
CSC 143F 1 CSC 143 Constructors Revisited. CSC 143F 2 Constructors In C++, the constructor is a special function automatically called when a class instance.
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.
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
Topics: Templates Exceptions
What Is? function predefined, programmer-defined
Programming with ANSI C ++
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?
How to be generic Lecture 10
C++ Templates.
Template Classes CMPS 2143.
Templates.
7. Inheritance and Polymorphism
FUNCTIONS 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?
Templates.
Templates in C++.
Chapter 2 Objects and Classes
Chapter 5 Function Basics
More About Data Types & Functions
CMSC 202 Templates.
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
CMSC 202 Lesson 22 Templates I.
Abstraction: Generic Programming, pt. 2
Polymorphism CMSC 202, Version 4/02.
CISC/CMPE320 - Prof. McLeod
C++ Templates CSE 333 Summer 2018
Parasol Lab, Texas A&M University
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Templates I CMSC 202.
Java Programming Language
Really reusable software
CMSC 341 C++ and OOP.
CMSC 202 Lesson 6 Functions II.
What Is? function predefined, programmer-defined
Templates Generic Programming.
Templates An introduction.
Class rational part2.
CMSC 341 C++ and OOP.
Constructors & Destructors
Templates Generic Programming.
Copy Constructors and Overloaded Assignment
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Templates CMSC 202, Version 4/02

A Form of Polymorphism(?) Polymorphism: The ability of a variable, function, or 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 C++ has two types of parametric polymorphism: Function templates Class templates CMSC 202, Version 4/02

Function Templates Suppose you want to write a generic function with two arguments of the same type that returns the largest of the two. You 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); CMSC 202, Version 4/02

Function Templates (con’t) 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. (Note: the < operator may have to be overloaded, e.g., if Foo is a class.) CMSC 202, Version 4/02

Function Templates (con’t) 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 type parameter and can have any legal identifier name. CMSC 202, Version 4/02

max( ) for int 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; } CMSC 202, Version 4/02

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; } CMSC 202, Version 4/02

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; } CMSC 202, Version 4/02

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 calling a template function. CMSC 202, Version 4/02

Can max( ) Be Created for Any Data Type? Answer -- Almost Note that max ( ) includes the statement if ( a < b ) . . . If the data type is a class, that class must support the < operator (i.e., it must be overloaded). CMSC 202, Version 4/02

Can max( ) Be Created for Any Data Type? (con’t) When the compiler sees this code: char *str1 = “abc”; char *str2 = “def”; cout << max(str1, str2) << endl; it creates this function: char* max (const char*& a, const char*& b) { if (a < b) // What gets compared? return b; else return a; } CMSC 202, Version 4/02

A Workaround We 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. CMSC 202, Version 4/02

Class Templates Templates can be provided for classes as well as functions. This is how we create generic classes that work with any data type (predefined or programmer-defined). This concept is also the basis (in C++) for container classes, classes that hold collections of objects. (Look out in CMSC 341!) CMSC 202, Version 4/02

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 }; CMSC 202, Version 4/02

Nothing Special About a smartArray of ints Nothing in the code for the smartArray relies on the fact that this is an array of integers. 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). CMSC 202, Version 4/02

smartArray Template template <class T> class smartArray { public: smartArray ( int size = 100 ); // other members private: int _size; T *_theData; // array of any type }; CMSC 202, Version 4/02

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 T’s for (int j = 0; j < _size; j++) // just to be nice _theData [ j ] = T( ); // default object } CMSC 202, Version 4/02

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 ]; } CMSC 202, Version 4/02

Another Example - operator [ ] template <class T> T smartArray<T>::operator[ ] (int index) { return _theData [ index ] ; } CMSC 202, Version 4/02

Using smartArray In the main program, Define some smartArrays: #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 needed class code. CMSC 202, Version 4/02

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 CMSC 202, Version 4/02

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 file.H will be in file.C -- they assume the same “root” filename. The g++ compiler isn’t that smart. CMSC 202, Version 4/02

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 CMSC 202, Version 4/02

smartArray.H #ifndef SMARTARRAY_H #define SMARTARRAY_H template <class T> class smartArray { public: smartArray ( int size = 100 ); // other members private: int _size; T *_theData; }; #include “smartArray.C” #endif CMSC 202, Version 4/02

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 (or smartArray.C) will never create a meaningful max.o (or smartArray.o), so we don’t include rules for making max.o (or smartArray.o) in our makefile. The code will be generated when the compiler encounters the code that uses the class template. CMSC 202, Version 4/02

More About Compiling We may want to compile max.C (smartArray.C) to check for syntax errors (using the -c switch), but this must be 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 syntax errors. 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. CMSC 202, Version 4/02

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. CMSC 202, Version 4/02