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

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 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 Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Intro to Generic Programming Templates and Vectors.
Templates CS212 & CS-240. Reuse Templates allow extending our classes Allows the user to supply certain attributes at compile time. Attributes specified.
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.
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.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
Lecture 6 : Intro. to Generic Programming Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
 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 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.
Motivation for Generic Programming in C++
C++ Lesson 1.
Chapter 22 - C++ Templates
Programming with ANSI C ++
Mark Redekopp David Kempe
How to be generic Lecture 10
C++ Templates.
Template Classes and Functions
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Chapter 5 Function Basics
Intro to Data Structures
Templates.
Templates in C++.
group work #hifiTeam
Templates ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY.
Templaets It is a new concept which enables us to define “generic class “ and “generic function” to provide the “ generic programming” We are familiar.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Templates Class Templates
Introduction to Programming
CSC 143 Stacks [Chapter 6].
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Today’s Topic Const Ref:
Parasol Lab, Texas A&M University
template< class T > class Stack { public:
Yan Shi CS/SE 2630 Lecture Notes
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<typename T> 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<class T> 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<typename T> T max(const T& a, const T& 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<< max<double>(4,5.5); // OK

More than one argument template<typename T1, typename T2> void print_max(const T1& a, const T2& b) { cout<< ((a > 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<typename T> class thing { public: thing(T data); ~thing() { delete x; } T get_data() { return *x; } T set_data(T data); private: T* x; }; thing<T>:: thing(T data) { x = new T; *x = data; } T thing<T>::set_data(T data) *x = data; #include <iostream> #include <string> using namespace std; main() { thing<int> i_thing(5); thing<string> 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''); }

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<typename T> class List_Node and a container class class List that uses List_Node. Note the line friend class list<T> in the definition of List_Node.

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

Class Templates : List Using the List_Node<T> class, we define our list class template: template<typename T> class List { public: List(); void append(const T& item); // Other member functions private: List_Node<T>* head_m; List_Node<T>* tail_m; }; List<T>::List():head_m(0),tail_m(0){} template<typename T> void List<T>::append(const T& item) { List_Node<T>* new_node = new List_Node<T>(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<Person> people; Person person(“JaneDoe”); people.append(person); people.append(Person(“JohnDoe”)); List<int> 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<int>(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<int> primes; // OK primes.append(2);

Common Errors template <class T> T* create() { ... } ; template <class T> void f() { T a; ... } With the template definition above, what is the function type of the following calls? create();// Error! Use e.g. create<int>() instead f();// Error! Use e.g. f<float>() 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<typename T> 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<int> intStack(5); intStack.push(5); intStack.push(8); intStack.pop(x); intStack.pop(y); cout << x << endl; cout << y << endl; return 0; }