CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
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.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
Object Oriented Data Structures
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Agenda Review Unix Review Algorithms Your first program Compiling programs What are functions? What is Object Oriented Programming? Variables Data Types.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)‏
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
1 C++ Syntax and Semantics, and the Program Development Process.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Fundamental Programming: Fundamental Programming Introduction to C++
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Lecture 19 CIS 208 Wednesday, April 06, Welcome to C++ Basic program style and I/O Class Creation Templates.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Overview of C++ Templates
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
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
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
MAITRAYEE MUKERJI Object Oriented Programming in C++
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++
C++ Lesson 1.
Andy Wang Object Oriented Programming in C++ COP 3330
Introduction to C++ (Extensions to C)
C++ Templates.
Introduction to C++ Systems Programming.
Motivation and Overview
Pointers and Pointer-Based Strings
Generic Programming Techniques in C++
Templates.
Object-Oriented Programming (OOP) Lecture No. 32
Pointers, Dynamic Data, and Reference Types
CMSC 202 Lesson 22 Templates I.
Andy Wang Object Oriented Programming in C++ COP 3330
C++ Pointers and Strings
Overview of C++ Polymorphism
Pointers and Pointer-Based Strings
Templates I CMSC 202.
Pointers and dynamic objects
C++ Pointers and Strings
Presentation transcript:

CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements –Otherwise, the code won’t compile (and errors will say why) The set of requirements imposed is called a concept Any specific type that meets the requirements is a model of that concept What requirement(s) does the expression return first; impose? What about while(first != last && *first != value) { ++first; } const T & Iterator

CSE 332: C++ template examples Interface Polymorphism: Concept Refinement A concept C is a refinement of concept D if C imposes all of the requirements of D Modeling and refinement satisfy three formal properties –Reflexivity: A concept refines itself –Containment: if T models C and C refines D then T models D –Transitivity: If C refines D then C refines any concept D refines What in the OO paradigm is this like? How does it differ? C1 C2 T1T2 T3T4 C0 containment transitivity can substitute, e.g., T3 for T1

CSE 332: C++ template examples One Last Detail: Associated Types template class Array : public ArrayBase { public: typedef T* iterator; Array(const int size); ~Array(); iterator begin () { return m_values;} iterator end () { return m_values+m_size;} private: T * m_values; }; void foo { Array a; fill_array(a); for (Array ::iterator i = a.begin(); i != a.end(); ++i) { cout << *i << “ ” << endl; } A type parameter is not concrete until its instantiated The compiler can work around that in many cases But sometimes the compiler needs more information Additional information can be associated with a type –For example, a class template can define an iterator type –Available to the template and code that uses the template –More about how this is done (and why) in later lectures

CSE 332: C++ template examples C++ Templates and Interface Polymorphism Two examples –Function template for printing different types –Class template for a linked list First example will refine a program several times –Ending up with a specialized reusable function template –Shows how to write general and specialized templates Second example will walk through finished code –Look at how to declare and define a class template –Look at another data structure that uses dynamic memory –A few practicalities you may need to know about E.g., including template source, working around compiler issues

CSE 332: C++ template examples First Example: Printing Different Types #include using namespace std; int main (int, char *[]) { int i = 7; bool b = false; int * ip = &i; char * cp = "hello, world!"; void * vp = cp; cout << "i is " << i << endl; cout << "b is " << b << endl; cout << "ip is " << ip << endl; cout << "cp is " << cp << endl; cout << "vp is " << vp << endl; return 0; } Large number of types in C++ Each handled a bit differently For example, << with ostream Simply giving to cout gives i is 7 b is 0 ip is 0xfef69094 cp is hello, world! vp is 0x8048a3c Let’s make some improvements

CSE 332: C++ template examples Improve the Output for bool #include using namespace std; int main (int, char *[]) {... cout << "i is " << i << endl; cout << "b is " << boolalpha << b << endl; cout << "ip is " << ip << endl; cout << "cp is " << cp << endl; cout << "vp is " << vp << endl; return 0; } First, fix how bool is output Use an iostream manipulator std::boolalpha –prints true or false –Instead of 1 or 0 Now we get i is 7 b is false ip is 0xfef2aa04 cp is hello, world! vp is 0x8048b0c But what about the pointers?

CSE 332: C++ template examples Improve the Output for Pointers #include using namespace std; int main (int, char *[]) {... cout << "i is " << i << endl; cout << "b is " << boolalpha << b << endl; cout << "ip is " << ip << " (points to " << *ip << ")" << endl; cout (cp) << " (points to \"" << cp << "\")" << endl; cout << "vp is " << vp << endl; return 0; } Now, fix pointers Use reinterpret_cast –Convert char * to void * Use dereferencing –Convert int * to int Now we have what we want i is 7 b is false ip is 0xfef23584 (points to 7) cp is 0x8048b70 (points to "hello, world!") vp is 0x8048b70 But, don’t want to have to do all that over again –Next time we want to print

CSE 332: C++ template examples Refactor the Code with a Function Template #include using namespace std; #include "common_T.h" int main (int, char *[]) { int i = 7; bool b = false; int * ip = &i; char * cp = "hello, world!"; void * vp = cp; print(cout, "i is ", i); print(cout, "b is ", b); print(cout, "ip is ", ip); print(cout, "cp is ", cp); print(cout, "vp is ", vp); return 0; } Define print function template –Consistent interface across types –Just pass message, variable With this template we get i is 7 b is 0 ip is 0xfeea28f4 cp is hello, world! vp is 0x8048adc Right back where we started? template void print (ostream & os, const char * message, const T & t) { os << message << t << endl; }

CSE 332: C++ template examples Template Specialization: More Polymorphism typedef char * charptr; typedef int * intptr; template <> void print (ostream & os, const char * message, const bool & b) { os << message << std::boolalpha << b << endl; } template <> void print (ostream & os, const char * message, const charptr & s) { os << message (s); if (s != 0) { os << " (points to \"" << s << "\")"; } os << endl; } template <> void print (ostream & os, const char * message, const intptr & ip) { os << message << ip; if (ip != 0) { os << " (points to " << *ip << ")"; } os << endl; } Specialize on individual types bool char * int * –Notice the use of typedef With specialization, we get i is 7 b is false ip is 0xfeebf064 (points to 7) cp is 0x8048c30 (points to "hello, world!") vp is 0x8048c30 And, we can reuse the solution! template void print (ostream & os, const char * message, const T & t) { os << message << t << endl; }

CSE 332: C++ template examples Concluding Remarks (1 of 2) The set of requirements that a class template or function template places on its parameterized types is called a concept in generic programming terminology Any type that meets those requirements is said to model the concept, and can be used in that template Concept refinement supports interface polymorphism Push common code and variables up into non- template base classes –Can help avoid subtle type errors –Can help reduce the size of the executable program Associated types expand the power of templates –E.g., used extensively in the C++ Standard Template Library

CSE 332: C++ template examples Concluding Remarks (2 of 2) Summary of generic programming ideas –Can use templates to plug different types into function and class declarations/definitions –Can look at template code to come up with what the requirements are for its parameterized types Fortunately, someone has already done that for the STL See Matt Austern’s book (CSE 532) for more details