Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.

Slides:



Advertisements
Similar presentations
Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Function and Class Templates.
 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.
Templates. Class templates – why? Writing programs we often use abstract data types such as stack, queue or tree. Implementations of these types may be.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
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.
Object Oriented Data Structures
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
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 =
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Java generics.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
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.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
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.
5th MaCS Debrecen On the Turing-Completeness of Generative Metaprograms Zoltán Porkoláb, István Zólyomi Dept. of Programming.
Chapter 22 - C++ Templates
Objects as a programming concept
Programming with ANSI C ++
Chapter 14 Templates C++ How to Program, 8/e
CS212: Object Oriented Analysis and Design
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Advanced Program Design with C++
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Templates I CMSC 202.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
More C++ Concepts Exception Handling Templates.
Presentation transcript:

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates metaprogramming Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Metaprogramming is about writing programs that can take programs as objects to be computed. A metaprogram is a program that can read, write, analyze, generate or change programs. metalanguage : language in which a metaprogram is written. object language : language used to express manipulated programs. If the metalanguage is also the object language, this allows to write programs that can change themselves, which is also known a reflective programming. Metaprogramming has been long part of programming languages, starting from Lisp in the early 1960s, that allowed a program to call its own interpreter to execute a string as a program, and thus allowing a program to generate an execute programs and thus invent/change its own execution. Reflective programming took a different flavor in the 1970s with the development of systems like Smalltalk, whose compiler and runtime system was written in Smalltalk itself, which allowed its runtime system to manipulate Smalltalk programs as objects. Nowadays, many “dynamic languages” allow some form of reflective programming. Metaprogramming Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Template metaprogramming is a particular kind of metaprogramming technique in which templates written in a metalanguage are used by a pre-compiler to generate temporary code in a specific programming language, which is then compiled by the main compiler along with the regular source code. The template is first declared using a meta language. When it is referred to in some code in a particular context (either in regular source code or in another template), it is instantiated to this particular context of use through object code generation. The instance is then a normal object code component that can be compiled/linked with other software components written in the source language. Any time the same template is used somewhere else with the same context, the previously generated instance is used. In template metaprogramming, from the perspective of the metaprogram, the generated source code is the object language. In many implementations, the metalanguage is a hybrid language that allows the use of the object language in the metaprograms, as well as to use metaprogram instances in the object language. Template metaprogramming Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering C++ provides this feature, which enables the programmer to write and use templates written in a meta language that is a slight variation of C++, and that can use C++ in its definitions. C++ code with templates is thus a hybrid language. C++ templates are used to write type-abstract code that expresses a generic solution independently of some type of values used or manipulated by the solution. The most common kinds of templates are containers. For example, a stack is a container that has some behavior (top, push, pop) which is independent of the type of values stored in the stack. Writing a C++ template allows to write the logic of the code while making abstraction of some of the types involved in order to make this code applicable across different types. C++ templates Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering C++ templates: compilation process Joey Paquet, COMP Advanced Program Design with C++ When C++ code uses some templates, the compilation process is preceded by template metaprocessing: Reads the templates. Finds all uses of the template. Generates a concrete version of the template for each different context of use. Links uses of the template with the correct concrete version. Normal compilation is applied to the generated/altered code.

Concordia University Department of Computer Science and Software Engineering One might want to define a function max to return the maximum value between its two parameters, to be used as such: In order to make this work, three different functions are needed: For each type that we want max to be applicable to, we need to explicitly overload the max function. In many cases (such as this one), the implementation code remains the same and the only difference is the type of some value(s) used in the processing. C++ templates Joey Paquet, COMP Advanced Program Design with C++ void main() { cout << "max(10, 15) = " << max(10, 15) << endl; cout << "max('k', 's') = " << max('k', 's') << endl; cout << "max(10.1, 15.2) = " << max(10.1, 15.2) << endl; } int max(int a, int b) { return a > b ? a : b; } char max(char a, char b) { return a > b ? a : b; } float max(float a, float b) { return a > b ? a : b; }

Concordia University Department of Computer Science and Software Engineering A function template can be defined to achieve the same result: The template function declaration/definition is first registered by the compiler. Then, upon every use of the template function, the metaprocessor instantiates a version of the template depending on the context of use of the template and organizes proper linkage to each instantiated function. C++ templates Joey Paquet, COMP Advanced Program Design with C++ // template function declaration template T max(T a, T b) { return a > b ? a : b; } // uses of the function template triggers // template instances generation at compile-time void main() { cout << "max(10, 15) = " << max(10, 15) << endl; cout << "max('k', 's') = " << max('k', 's') << endl; cout << "max(10.1, 15.2) = " << max(10.1, 15.2) << endl; } // generated instances int max(int a, int b) { return a > b ? a : b; } char max(char a, char b) { return a > b ? a : b; } float max(float a, float b) { return a > b ? a : b; }

Concordia University Department of Computer Science and Software Engineering C++ template: template class example Joey Paquet, COMP Advanced Program Design with C++ //template class method definitions template Stack ::Stack(int s) { size = s > 0 && s < 1000 ? s : 10; top = -1; // initialize stack stackPtr = new T[size]; } // push an element onto the Stack template int Stack ::push(const T& item) { if (!isFull()) { stackPtr[++top] = item; return 1; // push successful } return 0; // push unsuccessful } // pop an element off the Stack template int Stack ::pop(T& popValue) { if (!isEmpty()) { popValue = stackPtr[top--]; return 1; // pop successful } return 0; // pop unsuccessful } // template class declaration template class Stack { public: Stack(int = 10); ~Stack() { delete[] stackPtr; } int push(const T&); int pop(T&); int isEmpty()const { return top == -1; } int isFull() const { return top == size - 1; } private: int size; int top; T* stackPtr; }; // use of template class // triggers template instantiation void main() { Stack fs(5); float f = 1.1; while (fs.push(f)) { cout << f << ' '; f += 1.1; } while (fs.pop(f)) cout << f << ' '; Stack is; int i = 1.1; while (is.push(i)) { cout << i << ' '; i += 1; } while (is.pop(i)) cout << i << ' '; }

Concordia University Department of Computer Science and Software Engineering A great limitation of templates is that their applicability across different types is bound by the meaningfulness of the code that they use for all types that they will eventually be used for. Take our previous example max function template, which we might later want to use for strings: Here the problem is that applying the > operator on a char* (type of "Foo" and "Bar" ) compares the pointer values, not the strings that they point to, leading to incorrect result. We need to redefine the code for the implementation of max to use a comparison operation/function that also applies to char*. However, such an operation might not exist, leading us to write type-dependent code. Template specialization Joey Paquet, COMP Advanced Program Design with C++ template T max(T a, T b) { return a > b ? a : b; } void main() { cout << "max(10, 15) = " << max(10, 15) << endl; cout << "max('k', 's') = " << max('k', 's') << endl; cout << "max(10.1, 15.2) = " << max(10.1, 15.2) << endl; cout << "max("Foo", "Bar") = " << max("Foo", "Bar") << endl; }

Concordia University Department of Computer Science and Software Engineering Alternately, we can also use the notion of template specialisation to provide an alternate implementation for a specific instance of the template: This defines a specific instance of the function template max that is applicable when both parameters are of type char*. Template specialization Joey Paquet, COMP Advanced Program Design with C++ template <> char* max(char* a, char* b) { return strcmp(a, b) > 0 ? a : b; }

Concordia University Department of Computer Science and Software Engineering The same concept can be applied to template classes This defines a specific instance of the template class Formatter that is applicable when the parameters is of type char*. Template specialization Joey Paquet, COMP Advanced Program Design with C++ // Template class declaration and definition template class Formatter { T* m_t; public: Formatter(T* t) : m_t(t) { } void print() { cout << *m_t << endl; } }; // Specialization of template class // for type char* template<> class Formatter { char** m_t; public: Formatter(char** t) : m_t(t) { } void print() { cout << "Char: " << **m_t << endl; } }; int main() { int i = 157; // Use the generic template with int as the argument. Formatter formatter1(&i); char str[10] = "string1"; char* str1 = str; // Use the specialized template. Formatter formatter2(&str1); formatter1.print(); // 157 formatter2.print(); // Char value : s }

Concordia University Department of Computer Science and Software Engineering Each template class instance has its own copies of any static variables or members. Here, X has its own static member int s, which is shared by all instances of the type X. X has its own static member char* s, which is shared by all instances of the type X. Static data members are initialized outside of the class declaration (as are static members of regular classes) using the following syntax: Each template function instance has its own copy of any static local variables declared in a function template: C++ templates and static data members and local variables Joey Paquet, COMP Advanced Program Design with C++ template class X { public: static T s ; }; int main() { X xi ; X xc ; } template <> int X ::s = 3 ; template <> char* X ::s = "Hello" ; int main() { X xi ; cout << "xi.s = " << xi.s << endl ; X xc ; cout << "xc.s = " << xc.s << endl ; return 0 ; } template void f(T t) { static T s = 0; s = t ; cout << "s = " << s << endl ; } int main() { f(10) ; f("Hello") ; return 0 ; }

Concordia University Department of Computer Science and Software Engineering References Joey Paquet, COMP Advanced Program Design with C++