1 Joe Meehean.  Suppose we wanted a class to store a pair of ints  Access the first using first()  and the second using second()  Lets call it LCPair.

Slides:



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

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.
Chapter 17 Templates. Generic Algorithms Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.
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.
Generics. DCS – SWC 2 Generics In many situations, we want a certain functionality to work for a variety of types Typical example: we want to be able.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
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; }
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
 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.
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. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
Classes. Class expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Intro to Generic Programming Templates and Vectors.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Templates CS212 & CS-240. Reuse Templates allow extending our classes Allows the user to supply certain attributes at compile time. Attributes specified.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Java Generics.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
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 =
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Learners Support Publications Classes and Objects.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
 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.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Overview of C++ Templates
1 Chapter 1 C++ Templates Sections 1.6 and Templates Type-independent patterns that can work with multiple data types –Generic programming –Code.
Chapter 3 Templates Saurav Karmakar Spring Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Basic Java Syntax Comments Basic data types Operators and assignment.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
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.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
Chapter 1 C++ Templates (Sections 1.6, 1.7). Templates Type-independent patterns that can work with multiple data types. Function Templates  These define.
1 Introduction to Object Oriented Programming Chapter 10.
C:\Temp\Templates 4 5 Use This Main Program 6.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
MAITRAYEE MUKERJI Object Oriented Programming in C++
CPSC 252 Templatization Page 1 Templatization In CPSC152, we saw a class vector in which we could specify the type of values that are stored: vector intData(
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
Programming with ANSI C ++
How to be generic Lecture 10
Templates.
Templates.
Using local variable without initialization is an error.
Java Programming Language
Lab4 problems More about templates Some STL
Templates Generic Programming.
CMSC 341 C++ and OOP.
Templates Generic Programming.
Presentation transcript:

1 Joe Meehean

 Suppose we wanted a class to store a pair of ints  Access the first using first()  and the second using second()  Lets call it LCPair 2

class LCPair{ public: LCPair(int a,int b) { this->first = a; this->second = b; } int& first() { return this->first_; } int& second() { return this->second_; } private: int first_; int second_; }; 3

 The type of the pair items doesn’t matter class doesn’t do anything with them  Suppose we wanted to make LC Pair type independent  How do we do it?  Do we have to write a different pair class for every data type? 4

 The type of the pair items doesn’t matter class doesn’t do anything with them  Suppose we wanted to make LC Pair type independent  How do we do it?  Do we have to write a different pair class for every data type? 5

template class LCPair{ public: LCPair(const Obj1& o1,const Obj2& o2) { this->first_ = o1; this->second_ = o2; } Obj1& first() { return this->first_; } Obj2& second() { return this->second_; } private: Obj1 first_; Obj2 second_; }; 6

 Need to declare what the generic/template types are template generic type must follow the typename keyword e.g., template can define multiple generic types using a list template  Then use the declared generic type like any other type 7

 When initializing a templated class must declare what types you want it to use refer to class using ClassName e.g., LCPair intPair;  Then use it like any other class 8

 Using a template class 9 int main(){ LCPair intPair; LCPair boolPair; LCPair mixedPair; mixedPair.first() = 7; mixedPair.second() = 4.5; int i = mixedPair.first(); float f = mixedPair.second(); }

 A class template is not a class it is a pattern for what will become a class when you declare a class template variable e.g., LCPair intPair; the compiler makes a whole new class file replaces all instances of template types with declared types e.g., Obj1 replaced with int does this for each different declaration LCPair & LCPair are classes 10

 What if we want to find the largest element in an array?  If the element overrides the > operator, the data type of the elements is irrelevant  Use Function Templates to solve this problem uses similar syntax to class templates 11

12 /** * Comparable must provide > operator */ template Comparable& findMax(Comparable* a, int size){ int maxIndex = 0; for(size_t i = 1; i < size; i++){ if( a[i] > a[maxIndex] ){ maxIndex = i; } return a[maxIndex]; }

 Compiler replaces all template types with actual types  If you use methods, constructors or operators on a template type e.g., a[i] > a[maxIndex] produces compile error if not defined on concrete types 13

 When using template types always specify required methods & constructors in comments e.g., /* Comparable must provide > operator */ assume the template type is a class e.g., Obj1 obj = 0; // NO, may not compile e.g., Obj1 obj; // YES 14

 We always declare our classes in a.h file  And define their methods in a.cpp file  Many compilers cannot do this with templates including Visual Studio and g++  Template classes must be completely defined in the.h file 15

16

17 /** * Comparable must provide > operator */ template Comparable& findMax(Comparable* a, int size){ int maxIndex = 0; for(size_t i = 1; i < size; i++){ if( a[i] > a[maxIndex] ){ maxIndex = i; } return a[maxIndex]; }

 What if we want findMax to work for more complex objects e.g., Student object has Name, GPA, GradDate what should > compare them on? what if we want to be able to find max Name OR max GPA all with one function? 18

 What if we want findMax to work for more complex objects e.g., Student object has Name, GPA, GradDate what should > compare them on? what if we want to be able to find max Name OR max GPA all with one function? 19

 Objects that act like functions may have no data require only one public method  Can make lots of different functors for same class  Using templates we can compare any element using any functor that takes that element as a parameter 20

21 // compare students by name class StudentNameCmp{ public: bool isGreaterThan( const Student& lhs, const Student& rhs){ return lhs.getName() > rhs.getName(); } }; // compare students by gpa class StudentGPACmp{ public: bool isGreaterThan( const Student& lhs, const Student& rhs){ return lhs.getGPA() > rhs.getGPA(); } };

22 /** * Comparator must provide * isGreaterThan(Object, Object) */ template < typename Object, typename Comparator> Object& findMax( Object* a, int size, Comparator cmp){ int maxIndex = 0; for(size_t i = 1; i < size; i++){ if( cmp.isGreaterThan(a[i],a[maxIndex]) ){ maxIndex = i; } return a[maxIndex]; }

23 int main(){ Student students[15]; // fill in array... // find the largest name Student maxName = findMax(students, 15, StudentNameCmp() ); // find the student with best GPA Student bestGPA = findMax(students, 15, StudentGPACmp() ); }

 Making functors look like functions  Instead of defining isGreaterThan method  Override the operator() known as the function call operator calling it looks just like calling a non-member function 24

25 // compare students by name class StudentNameCmp{ public: bool operator()( const Student& lhs, const Student& rhs){ return lhs.getName() > rhs.getName(); } }; // compare students by gpa class StudentGPACmp{ public: bool operator()( const Student& lhs, const Student& rhs){ return lhs.getGPA() > rhs.getGPA(); } };

26 /** * Comparator must provide * function operator */ template <typename Object, typename Comparator> Object& findMax( Object* a, int size, Comparator cmp){ int maxIndex = 0; for(size_t i = 1; i < size; i++){ if( cmp.isGreaterThan(a[i],a[maxIndex]) ){ if( cmp(a[i],a[maxIndex]) ){ maxIndex = i; } return a[maxIndex]; }

27