CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.

Slides:



Advertisements
Similar presentations
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Advertisements

CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
CSE 425: Semantics II Implementing Scopes A symbol table is in essence a dictionary –I.e., every name appears in it, with the info known about it –Usually.
Chapter 14: Overloading and Templates
. 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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
1 Introduction to C++ Programming Concept Basic C++ C++ Extension from C.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
CS 11 C++ track: lecture 8 Today: Inheritance. Inheritance (1) In C++ we create classes and instantiate objects An object of class Fruit "is-a" Fruit.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
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: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
OOP Languages: Java vs C++
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Programming Languages and Paradigms Object-Oriented Programming.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Templates Zhen Jiang West Chester University
 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.
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
Class Inheritance UNC-CHAPEL HILL COMP 401 BRIAN CRISTANTE 5 FEBRUARY 2015.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Programming Languages and Paradigms Object-Oriented Programming.
CSE 425: Object-Oriented Programming I Object-Oriented Programming A design method as well as a programming paradigm –For example, CRC cards, noun-verb.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
Overview of C++ Templates
Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
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.
1 CSE Programming in C++. 2 Overview Sign roster list Syllabus and Course Policies Introduction to C++ About Lab 1 Fill Questionnaire.
Overview of C++ Polymorphism
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
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.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
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.
 2006 Pearson Education, Inc. All rights reserved Templates.
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)
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
MAITRAYEE MUKERJI Object Oriented Programming in C++
Chapter 2 Objects and Classes
Motivation for Generic Programming in C++
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Procedural and Object-Oriented Programming
Motivation and Overview
Object-Oriented Programming (OOP) Lecture No. 45
Inheritance and Polymorphism
Templates.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Overview of C++ Overloading
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Overview of C++ Polymorphism
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned Readings –pages (function templates, specialization) –pages (class templates) –pages (nested class templates)

CSE 332: C++ templates Overview of C++ Templates Templates are used to plug in different types –Can re-use same code with int, string, etc. Also called “type parameterization” –Types are given as parameters to a template –Like variables are given as a function’s parameters Can make templates for functions and classes –The user of a class template must declare the type parameters when declaring an instance –Don’t have to declare the type parameters when calling a function template (call as though a non-template function) The compiler figures it out for you, based on function call signature

CSE 332: C++ templates Files for C++ Templates Keep declarations and definitions separate –Just as you would for non-template classes and functions –Have separate header (declarations) and source (definitions) files Separate template and non-template code –For example, if a template relates to a class, put template in header and source files with similar (but different) names array.h array.cc array_T.h array_T.cc Some compilers (like g++) require that template definitions be included with their declarations //... at the end of array_T.h #if defined (TEMPLATES_REQUIRE_SOURCE) #include "array_T.cc" #endif /* TEMPLATES_REQUIRE_SOURCE */ #endif /* ARRAY_T_H */

CSE 332: C++ templates Introduction to Function Templates template void swap(T &lhs, T &rhs) { T temp = lhs; lhs = rhs; rhs = temp; } int main () { int i = 3; int j = 7; swap (i,j); return 0; } Basic idea –same code is re-used for different types Function template swap –takes one type parameter, T Definition interchanges values of two passed arguments –of the parameterized type Compiler infers type is really int when swap is called Compiler instantiates the function template definition using type int

CSE 332: C++ templates Introduction to Class Templates template class Array { public: Array(const int size); ~Array(); private: T * values_; const int size_; }; int main() { Array a(10); Array b(5); return 0; } Parameterized type T must be specified in class template declaration –Both as a parameter, and where it’s used in the class When an instance is declared, must also explicitly specify the concrete type parameter –E.g., int vs. string in function main() –In previous function template example, didn’t have to say swap

CSE 332: C++ templates Tips on Using Function and Class Templates Push common code and variables up into non- template base classes –Gives compiler less work to do instantiating templates –Reduces program size and compilation time Use function templates when you want type parameterization to be “invisible” to programmer –To force an explicit declaration of the parameterized type, use member functions of class templates instead Use class templates when you want to parameterize member variables types –Lots of containers in the STL do this (vector, list, etc.) –We’ll talk about the STL and how it uses templates later in the semester

CSE 332: C++ templates Templates Have a Different View of Types template void swap(T &lhs, T &rhs) { T temp = lhs; lhs = rhs; rhs = temp; } int main () { int i = 3; int j = 7; swap (i,j); return 0; } Look at what swap requires of its parameterized types –Copy construction T temp = lhs; –Assignment lhs = rhs; rhs = temp; These requirements are called a template’s concept A type that meets those requirements –is called a model of that concept Can substitute any type that models a templates concept

CSE 332: C++ templates Inheritance vs. Concept Refinement Explicit inheritance relation between classes –Class2 advertises its parent, Class1 Implicit refinement relation between concepts –Concept2 adds to the requirements of Concept1 Concept1 Concept2 T1T2 T3T4 refines models Class1 Class2 T1T2 T3T4 inherits from is an instance of

CSE 332: C++ templates Inheritance vs. Concept Refinement, part II Similarities –Both define a type hierarchy (a partial order) Reflexive and transitive, but not symmetric Can be expressed as a directed acyclic graph Can be used by a compiler to do type checking –Both support type substitution, polymorphism Differences –Again, refinement is implicit, inheritance is explicit Programmer must define all inheritance relationships C++ compiler infers concept/models relationships for us –Type substitution and polymorphism mechanisms

CSE 332: C++ templates OO vs. Generic Programming Paradigms Liskov Substitution Principle –If S is a subtype of type T (S meets all the requirements of T), then whenever we need an instance of T we can substitute an instance of S. Object-Oriented (OO) Programming: Public Inheritance class S: public T { … }; foo (T & t); S s; foo (s); Generic Programming: Concepts, Models, Refinement –Class A only supports default construction –Class B supports assignment and copy construction as well as all other operators A support –Can use B in any template whose concept A models –Cannot use A in any template whose concept B models

CSE 332: C++ templates Extending Interfaces Substitution is often non-symmetric –S replaces T, but not vice versa –Often due to S extending the interface T provides In OO Programming: again Public Inheritance class T {public: void baz ();}; // T only has baz class S: public T {public: void bar ();}; // S has baz and bar In Generic Programming: again Concept Refinement –An STL random access iterator provides +=, -=, and ++ For example, an iterator using a pointer into an array –An STL forward iterator provides ++ but some forward iterators may not provide += or -= For example an iterator using a pointer into a linked list

CSE 332: C++ templates Polymorphism with Templates Substitution may provide different behaviors –“Poly” = many + “Morph” = form –When we can substitute types, we want to get specialized behaviors when using different types In OO programming –Derived classes can override base class behaviors –Using virtual functions, we get polymorphism Can we do something similar with Concepts and types that model them in templates? –I.e., so we get customized behavior for specific (more refined) templates?

CSE 332: C++ templates Specializing Behaviors of Types What mechanisms are available in C++? With OO programming –We combine public inheritance & virtual methods: class T {public: virtual void foo () {cout << “T”;} }; class S: public T {virtual void foo () {cout << “S”;}}; With Generic programming –We combine operator/function overloading with template specialization mechanisms –Sometimes called “interface polymorphism”

CSE 332: C++ templates Template Specialization Allows us to override behaviors –Of function templates or class templates Can override default (base) behavior: template print (T t) {cout << t << endl;} template <> print (char * str) {cout << (void *) str << endl;} Partial specialization possible (some compilers) –Leave types of some parameters unspecified –While specializing on explicit types for others –E.g., on a null_guard type to remove acquire and release overhead if no dynamic allocation is done

CSE 332: C++ templates Review Questions How are inheritance-based (OO) and interface- based (generic) substitution similar, and how do they differ? What are the similarities and differences between type polymorphism with inheritance (OO) and with concepts (generic)? How does C++ template specialization work? How do you declare/define a generic template, and different specializations of it?

CSE 332: C++ templates For Thursday Make sure you’re caught up on the readings –pages (function templates, specialization) –pages (class templates) –pages (nested class templates) We’ll look at a number of code examples