Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.

Slides:



Advertisements
Similar presentations
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Function and Class Templates.
Stacks and Queues. Sample PMT online… Browse 1120/sumII05/PMT/2004_1/
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Stacks  Standard operations: IsEmpty … return true iff stack is empty Top … return top element of stack Push … add an element to the top of the stack.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Intro to Generic Programming Templates and Vectors.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Templates Zhen Jiang West Chester University
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
EEL 3801 Part VIII Fundamentals of C and C++ Programming Template Functions and Classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
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 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Lecture 6 : Intro. to Generic Programming Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Computer Science and Software Engineering University of Wisconsin - Platteville 5. Template Yan Shi CS/SE 2630 Lecture Notes.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
 2003 Prentice Hall, Inc. All rights reserved. 1 Ders Notu 8 - Template İçerik 11.1 Giriş 11.2 Fonksiyon Template ları 11.3 Overloading Fonksiyon Templates.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Preprocessing Lecture 9 November 2, 2004.
Template Classes.
Chapter 22 - C++ Templates
Programming with ANSI C ++
Mark Redekopp David Kempe
How to be generic Lecture 10
C++ Templates.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Templates.
Templates in C++.
group work #hifiTeam
Templates ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Templates Class Templates
Introduction to Programming
CSC 143 Stacks [Chapter 6].
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Parasol Lab, Texas A&M University
template< class T > class Stack { public:
Template.
Lab4 problems More about templates Some STL
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Object-Oriented Programming (OOP) Lecture No. 34
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Templates An introduction.
Function Templates Class Templates
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
More C++ Concepts Exception Handling Templates.
Presentation transcript:

Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides

Function Template We often find a set of functions that look very much alike, e.g. for a certain type T, the max function has the form int max(const int& a, const int& b) { …} string max(const string& a, const string& b) { …} T max(const T& a, const T& b) { …} In C++, we can define one single function definition using templates: template T max(const T& a, const T& b) { return (a > b) ? a : b; }

Function Template The typename keyword may be replaced by class ; the following template definition is equivalent to the one above: template T max(const T& a, const T& b) { return (a > b) ? a : b; } Prefer the typename syntax (the class syntax is more old- fashioned). The above template definitions are not functions; you cannot call a function template.

Function Template Instantiation The compiler creates functions using function templates int i = 2, j = 3; cout << max(i, j); string a(“Hello”), b(“World”); cout<< max(a, b); In this case, the compiler creates two different max()functions using the function template template T max(constT& a, constT& b); This is called template instantiation. There is no automatic type conversion for template arguments cout<< max(3, 5);// T is int cout<< max(4.3, 5.6); // T is double cout<< max(4, 5.5); // Error cout (4,5.5); // OK

More than one argument template void print_max(const T1& a, const T2& b) { cout b) ? a : b) << endl; } void f() { print_max(4, 5.5);// Prints 5.5 print_max(5.5, 4);// Prints 5.5 }

Class Templates template class thing { public: thing(T data); ~thing() { delete x; } T get_data() { return *x; } T set_data(T data); private: T* x; }; template thing :: thing(T data) { x = new T; *x = data; } template T thing ::set_data(T data) { *x = data; } #include using namespace std; main() { thing i_thing(5); thing s_thing(“COMP151”); cout<< i_thing.get_data()<< endl; cout<< s_thing.get_data()<< endl; i_thing.set_data(10); s_thing.set_data(''CPEG''); cout<< i_thing.get_data()<< endl; cout<< s_thing.get_data()<< endl; }

Class templates The template mechanism works for classes as well. This is particularly useful for defining container classes. In the next few slides we will define template class List_Node and a container class template class List that uses List_Node. Note the line friend class list in the definition of List_Node.

Class templates : List_Node template class List_Node{ public: List_Node(const T& data); List_Node * next(); // Other member functions private: List_Node * next_m; List_Node * prev_m; T data_m; friend class List ; }; template List_Node ::List_Node(const T& data) : data_m(data), next_m(0), prev_m(0) { } template List_Node * List_Node ::next() { return next_m; }

Class Templates : List Using the List_Node class, we define our list class template: template class List { public: List(); void append(const T& item); // Other member functions private: List_Node * head_m; List_Node * tail_m; }; template List ::List():head_m(0),tail_m(0) {} template void List ::append(const T& item) { List_Node * new_node = new List_Node (item); if (! tail_m) { head_m= tail_m= new_node; } else { //... }

Class Templates : List Example Now we can use our brand new list class to store any type of element that we want, without having to resort to “code reuse by copying”: List people; Person person(“JaneDoe”); people.append(person); people.append(Person(“JohnDoe”)); List primes; primes.append(2); primes.append(3); primes.append(5);

Difference between class & function templates Remember that for function templates, the compiler can infer the template arguments: Int i = max(4, 5); Int j = max (7, 2);// OK, but not needed For class templates, you always have to specify the actual template arguments; the compiler does not infer the template arguments: List primes;// Error List primes; // OK primes.append(2);

Common Errors template T* create() {... } ; template void f() { T a;... } With the template definition above, what is the function type of the following calls? create();// Error! Use e.g. create () instead f();// Error! Use e.g. f () instead Reason: the compiler has to be able to infer the actual function types from calls to the template function.

Exercise Write a stack class with templates template class Stack { public: Stack(int = 100); ~Stack(); bool push(const T&); bool pop(T&); bool isEmpty() const; bool isFull() const; private: int size; int top; T *stackPtr; }; int main() { int x, y; Stack intStack(5); intStack.push(5); intStack.push(8); intStack.pop(x); intStack.pop(y); cout << x << endl; cout << y << endl; return 0; }