Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Lecture 18 Templates, Part II. From Last Time: What is a Template? This is the “official” specification for a template. It says that to define a template.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
 2006 Pearson Education, Inc. All rights reserved Templates.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
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.
Intro to Generic Programming Templates and Vectors.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Java and C++, The Difference An introduction Unit - 00.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
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 =
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Dynamic memory allocation and Pointers Lecture 4.
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
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:
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
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.
Overview of C++ Templates
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Introduction to Object-Oriented Programming Lesson 2.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
Overview of C++ Polymorphism
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Exception Handling How to handle the runtime errors.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
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.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
C++ Functions A bit of review (things we’ve covered so far)
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Motivation for Generic Programming in C++
Programming with ANSI C ++
7. Inheritance and Polymorphism
CS212: Object Oriented Analysis and Design
CMSC 202 Lesson 22 Templates I.
Abstraction: Generic Programming, pt. 2
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Overview of C++ Polymorphism
Templates I CMSC 202.
Templates An introduction.
Templates CMSC 202, Version 4/02.
COP 3330 Object-oriented Programming in C++
Presentation transcript:

Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization

2 Overview  Introduction to templates  Function templates  Class templates  Class member template  Template separate compilation  Applications

Department of Computer Science and Engineering, HKUST 3 Template Introduction

4 Template – code reuse, again  Inheritance is sometimes very helpful to reuse code, BUT it cannot be used to customize “type”, for example: class IntList { public: int& get(int v); // other methods … };  You can’t inherit this class to have a List of strings, for example. The get() method must return an integer reference.

5 Idea: making type a parameter  With template, you can make type a parameter.  It would be good if we can write code like this: T max(T v1, T v2) { if (v1 > v2) { return v1; } else { return v2; }  Notice T is a type parameter that can be substituted with whatever type. But the type has to be comparable. (i.e. has the operator> defined)  You can write max(4, 5), in this case it will return 5 as an int.  You can also write max(3.3, 2.7), in this case it will return 3.3, which is a double.

6 Template in details (1)  A template is a piece of code that contains some type variable. The type variable is called generic type. It will be replaced, at compilation time, to a particular type.  The process of replacement is called instantiation. After replacement, the code is free of type variable, and therefore just like any normal code, it can be compiled and executed.  So, what code can be used as template? A template can be a function template, where a the piece of code is a function, or otherwise It could be a class template, where is the type variable is used all over the class. Sometimes, when only a method want to be template, we can also define class member template.

7 Template in details (2)  In C++, template also allows different types to be instantiated differently, in case there is difficulty to write a piece of code to fit all possible types.  That is called template specialization. You usually don’t want to specialize template when it is unnecessary.

Department of Computer Science and Engineering, HKUST 8 Function Template Basic Syntax Instantiation Specialization The need and impossibility for partial specialization

9 Function template (1)  Code example speak a thousand words, let get down to an example. 1: template 2: T maximum (T v1, T v2) { 3: if (v1 > v2) { 4: return v1; 5: } else { 6: return v2; 7: } 8: }

10 Function template (2)  Line 1: template This line declares the coming block of code (in this case, the function max) is a template, it has a single type parameter named T.  Line 2 ~ 8: just imagine T is replaced by int, then the code can be clearly understood. It is just a simple implementation of the maximum(int, int) function.

11 Function Template Instantiation (1)  When template code are invoked, they’re instantiated The type parameter is substituted with an appropriate type Then the code is appended to the main code and compiled.  What is the appropriate type?

12 What is the appropriate type?  The basic idea is, every type in the parameter list need to matches with the template parameter.  NO automatic casting is done.  e.g. maximum(3, 4.5) CANNOT compile. maximum(3, 2) can compile, where T instantiated as int. maximum(3.5, 4.2) can compile, where T instantiated as double.

13 Explicit Instantiation  What if I really want to call: maximum(3, 4.5)?  You can call it this way: maximum (3, 4.5), or maximum((double)3, 4.5)  The use of maximum is called explicit instantiation. The programmer explicitly specify how the template should be instantiated.

14 More than a single template parameter  More than one template parameter.  With this program, I can call max(3, 4.5) template void maximum (T a, U b) { if (a > b) { cout << a << endl; } else { cout << a << endl; }

15 Specialization (1)  What if some people implemented a class called Money, which ONLY support a function: bool larger(const Money& another);  In this case, you cannot call like this: Money m1(3), m2(2) maximum(m1, m2);  The compilation fails: no operator> defined for class Money.  If you can’t alter the Money class (because it was written by your boss), then you will need to use specialization.

16 Specialization (2) – the Money class That’s what your boss have written. class Money { public: Money(double value) : _value(value) {} double value() const { return _value; } bool larger(const Money& m) const { return _value > m._value; } private: const double _value; }; ostream& operator<<(ostream& os, const Money& m) { os << “$” << m.value(); }

17 Specialization (3)  You can explicitly write the instantiated version, to avoid the compiler instantiate something that does NOT compile.  Since the Money class does NOT support the comparison operators, then template<> Money max (Money x, Money y) { if (x.larger(y)) { return x; } else { return y; }  The first template<> is required by the compiler, although it isn’t very meaningful in function templates.

18 The concept of partial specialization  Now, we are more greedy, could we write a function that compare Money and integer?  Of course, your boss is still there, you can’t write the global operator function.  Now, let’s try: template<> void maximumPrint (Money a, int b) { if (a.value() > b) { cout << a << endl; } else { cout << b << endl; }  Notice the use of cout instead of return, it is done because of the return type.

19 How about other comparisons?  Now the code work when Money compares with integer, it cannot compare with double, it also cannot compare with long.  What is the ideal? Specialize once and make these all work by ONLY specialize the first parameter. Which is something like this: template void maximumPrint (Money a, T b) { if (a.value() > b) { cout << a << endl; } else { cout << b << endl; }  This is impossible in C++ - we will solve it later, after we learn more. error: partial specialization `maximumPrint ' of function template

Department of Computer Science and Engineering, HKUST 20 Class Template Basic Syntax Instantiation Specialization Partial specialization

21 Class Template  Making the whole class a template Having a type variable usable throughout the whole class.  The idea is very similar with function template.  Let’s look at an example.

22 Templated Array Class template class Array { public: Array(int s) { storage = new T[_size = s]; } ~Array() { delete[] storage; } T& get(int i) { return storage[i]; } const T& get(int i) const { return storage[i]; } void process(); private: T* storage; int _size; }; template void Array ::process() { for (int i = 0; i < _size; i++) { storage[i].process(); }

23 Syntax Highlight  Similar with function templates, the declaration of a template class start with the template parameter list template  In a template class, method do NOT necessarily inline. The method process() is written outside the class.  In each template class method implementation, the SAME template parameter list should be used in process()

24 Class Member Instantiation  Class fields are ALWAYS instantiated when an object is constructed, BUT  member functions are NOT, they are instantiated ONLY when they are called.  Example: class V { public: void process() { cout << “Hello” << endl; } };  This is valid!! Array a(3); cout << (a.get(1) = 7) << endl; Because the Array ::process() is NOT called and hence NOT instantiated.  This is also valid, for sure Array a(3); a.process();

25 Template Induced Interface  In order to successfully use the Array class, the template argument should conform to some standard.  For example, a process() member function must be defined in order to call process() BUT: There is NO restriction on the return type.  A template induced interface is more flexible than an abstract base class (ABC)

26 Class Template Specialization (1)  Similar to function template specialization, class template can also be specialization.  Say, for example, that you cannot change class U (again, that is written by your boss), but the process function of U sadly requires a dummy integer parameter.  We could have specialize the class template to solve this problem

27 Class Template Specialization (2) The class U – written by your boss again class U { public: void process(int x) { //... do something, not interesting... } };

28 Template member specialization  We can specialize the template member by: void Array ::process() { for (int i = 0; i < _size; i++) { storage[i].process(0); }

29 Class Template Partial Specialization The basic class template  Unlike function template, class template can be partially specialized.  We will try to use this to solve the money comparison problem we encountered before. template class Maximum { public: Maximum(T a, U b) { if (a > b) { cout << a << endl; } else { cout << b << endl; } private: };

30 The partial specialization Comparing Money with numerical type template class Maximum { public: Maximum(Money a, U b) { if (a.value() > b) { cout << a << endl; } else { cout << b << endl; } private: };

31 The complete specialization Comparing two money objects template<> class Maximum { public: Maximum(Money a, Money b) { if (a.larger(b)) { cout << a << endl; } else { cout << b << endl; } };

32 Testing Code int main() { Money m1(5.5), m2(4.0); Maximum (1, 2); Maximum (m1, 7); Maximum (m1, m2); return 0; }

33 Class Member Template  There is situation there is only a method you want to template it. Honestly, this is a rare situation.  The template declaration of this type is very similar to a function template, as an example: class Simple { public: template bool larger(const T& a, const T& b) { … } };

34 Class Template Partial Specialization  In template specialization, we solve problem that a particular class template argument cannot be changed to satisfy the template induced interface.  In case of multiple template argument, we can specialize a single type parameter and leave the remaining unchanged.  Example: U& Array:: get(const T& t) { … }  This is NOT possible with function templates. NO function template partial specialization.

Department of Computer Science and Engineering, HKUST 35 Template Template Separate Compilation

36 Template Separate Compilation  Templates need to be instantiated at compile time, therefore, the template must be available at the same time when the template is instantiated.  Object file do NOT contain the template source, that why it is difficult to separate compile templates.  Simple answer: Template CANNOT be compiled separately.  Complex answer: Template CAN be compiled separately by the ANSI specification using the export keyword

37 Precompiled Headers  If the template is large, then using it incurs large overhead because the same template is compiled again and again.  Some compilers support compiling the header once and store the compiled header.  Headers.html

Department of Computer Science and Engineering, HKUST 38 Template Applications

39 Application of Template  Standard Template Library (STL) A set of library classes, widely used, will be covered in next set of slides.  auto_ptr An implementation of smart pointer that can point to any type of object.  Various type of casting static_cast dynamic_cast const_cast

40 auto_ptr (1)  A standard smart pointer implementation in C++.  Usage: void createUseAndDelete() { auto_ptr pt(new T); pt->print(); }  The new object is AUTOMATICALLY deleted. That’s why we call it auto_ptr.  Of course, assumed T has a print method.

41 auto_ptr (2)  What if you do NOT want to delete the object. Option 1: Do NOT use auto_ptr!  Obvious! Isn’t it? Option 2: Use the release() method of auto_ptr.  T* pt2 = pt.release();  Now you will need to delete pt2 yourself, the object will NOT automatically.  Typically used when the object is conditionally cached.  If you want to know more about auto_ptr

42 Advanced Casting  Casting in C style is NOT safe. Slicing might occurs Casting to incorrect type might happens.  It is dangerous to cast away const in C style casting. const char* k = “x”; char* p = (char*)k; *p = ‘z’; // Leads to RUNTIME error  Casting can be template function object! Allows casting away const! Allow runtime checking of type.

43 static_cast  Static checking is performed before casting, if unsuccessful will lead to COMPILE error.  Example: const char* k = “x”; char* p = static_cast (k); // ERROR class B : public A { … }; class C {.. }; static_cast (new B); // compiles static_cast (new A); // compiles static_cast (new C); // NOT compiles Notice, 2nd case is NOT correct, but still compile, because there is NO way for the compiler to check that at COMPILE time. Static means compile time checking.

44 dynamic_cast  Overcome checking problem, delay the type check untils runtime.  Example: class A {virtual void x();}; class B : public A {}; class C : public A{}; A* b = new B(); A* c = new C(); dynamic_cast (b); // Compiles dynamic_cast (c); // Compiles  Virtual function? Dynamic cast only work ONLY on polymorphic class, which has at least one virtual function.  Case 2, still compile? It will return NULL, because the condition can be known only at runtime, the code can only response at runtime.

45 const_cast: cast away const safely #include using namespace std; class A { public: int getX() const { return x; } void setX(int _x) { this->x = _x; } private: int x; }; int main() { const A* a = new A(); A* b = const_cast (a); b->setX(20); cout getX() << endl; delete b; return 0; }