Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.

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++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
. 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.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Function and Class Templates.
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.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
 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.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
Review of C++ Programming Part II Sheng-Fang Huang.
Intro to Generic Programming Templates and Vectors.
OOP Languages: Java vs C++
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Constructors and Other Tools Version 1.0 Topics Constructors & Destructors Composition const Parameter Modifier const objects const functions In-line.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
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.
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.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
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 © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
 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.
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:
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
March 2006 Copyright, 2006 Oxford Consulting, Ltd C++ Templates Templates F Part of the ongoing development of the C++ language F Integral part.
1 CSC241: Object Oriented Programming Lecture No 25.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 22 - C++ Templates Outline 22.1Introduction.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
 Templates enable us to define generic classes and functions and thus provides support for generic programming. Generic types are used as parameters.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
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 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
 2006 Pearson Education, Inc. All rights reserved Templates.
Memory Management.
Programming with ANSI C ++
How to be generic Lecture 10
C++ Templates.
Templates.
Chapter 14 Templates C++ How to Program, 8/e
CMSC 202 Templates.
CMSC 202 Lesson 22 Templates I.
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Templates I CMSC 202.
Really reusable software
Templates An introduction.
Templates CMSC 202, Version 4/02.
Presentation transcript:

Templates

Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function template Use a function template in a program Explain how class templates are used Correctly create a class template Use class templates in a program

Function Templates Consider the following function: int biggest (int arg1, int arg2) { if (arg1 > arg2) return arg1; else return arg2; } this function very nicely finds the maximum of two integers. What if we also need a function to find the max of two floats?

Then we might write: float biggest (float arg1, float arg2) { if (arg1 > arg2) return arg1; else return arg2; }

int biggest (int arg1, int arg2) { if (arg1 > arg2) return arg1; else return arg2; } float biggest (float arg1, float arg2) { if (arg1 > arg2) return arg1; else return arg2; } Notice that the only thing different about these two functions are the data types of the parameters and the return type.

Since this is a really useful algorithm, we could continue to write versions for the other basic data types …. but there must be a better solution.

Creating a Function Template allows us to create a generic algorithm, that can be used for any parameter type.

template T biggest (T arg1, T arg2) { if (arg1 > arg2) return arg1; else return arg2; } the template prefix tells the compiler that this is a template, so treat it differently from a normal function. the type parameter. The identifier T is most often used, but any identifier is acceptable. return type is Targ1 and arg2 are of type T you may see the keyword typename instead of class

When the compiler sees this function template, it simply makes note of the fact that the template exists …. no code is generated.

When later on in your program, the compiler sees a function being invoked, such as int a, b, c;. c = biggest (a,b); The compiler looks for a function prototype that matches the invocation. Failing to find one, it then looks for a function template that will generate the proper function. It finds the function template and generates the code for the function.

template T biggest (T arg1, T arg2) { if (arg1 > arg2) return arg1; else return arg2; } int biggest (int arg1, int arg2) { if (arg1 > arg2) return arg1; else return arg2; } In this case, we needed a function that took two ints as parameters, so the compiler took the function template and replaced the type parameter T with the keyword int everywhere it appeared in the template. only this one definition gets generated for type int. Any subsequent invocation of biggest (int, int) will use this definition. an instance or production of the function template.

However, if later on in your program, the compiler sees a function being invoked, such as double x, y, z;. z = biggest (x,y); The compiler will create another function definition, replacing the type parameter T with the keyword double!

Summary A function template does not generate any code when it is encountered by the compiler. The compiler generates the code for the function from the template when it sees a function invocation for which there is no existing function that matches the signature of the call. The type parameter is replaced by the actual data type needed when the function is generated.

It is possible, although not often used, to create a function template with two or more type parameters, as template …

The type parameter need not always be replaced with one of the basic data types. Suppose, for example, that we wanted to find the maximum of two length objects. length lengthOne, lengthTwo, lengthThree;... lengthThree = biggest (lengthOne, lengthTwo);

Length biggest (Length arg1, Length arg2) { if (arg1 > arg2) return arg1; else return arg2; } The compiler would correctly generate Do you see any problems with the code that just got generated?

Length biggest (Length arg1, Length arg2) { if (arg1 > arg2) return arg1; else return arg2; } For efficiency, we would like to pass the parameters by reference unless we have overloaded the > operator in the Length class, the compiler won’t be able to generate any code here.

Some Rules of Thumb When creating a function template, pass parameters by reference so that when used with an object, the code is more efficient. When using a function template with an object, any operators used on the object must be overloaded in the object’s class definition.

Revised Function Template template const T& biggest (const T& arg1, const T& arg2) { if (arg1 > arg2) return arg1; else return arg2; }

Templates and Overloading All of the functions generated from a function template have the same name, with different parameter types. So, by definition, these functions are overloaded, and the compiler uses overloading resolution to find the right function to invoke. You could also define a function template with the same name, but with a different number of parameters.

Class Exercise: In groups of 2-3, write a function template that will do a bubble sort on an array of data. Test your program with a small driver. Try sorting an array of integers. Use the less than operator to compare elements of the array. Be prepared to discuss how you would sort an array of Employee objects.

Class Templates Just as we can generalize a function by writing a function template, we can generalize a class by writing a class template.

Container Classes Class templates are most often used to create container classes. Objects of a container class hold or organize data in useful ways. For example …

template class Box { private: T dataMember; public: Box (const T& data) : dataMember(data) { } void display ( ) { cout << “my content = “ << dataMember; } }; template prefix type parameter Keep in mind that this is not a class. It is only a template that the compiler can use to create a class, when it needs one.

the template name the type … replaces the type parameter in the class template the object name the constructor parameter Using the same mechanism as we did for a function template, the compiler generates no code when it encounters a class template, but generates a real class definition when it sees a statement like Box myBox (5);

this is the class name for the class just generated, usually pronounced “Box of ints”

A different class definition would be generated by the statement Box myName(“Roger”);

template class Box { private: T dataMember; public: Box (const T& data); void display ( ); }; template Box :: Box(const T& data) :dataMember(data) { } template void Box ::display( ) { cout << dataMember; } Writing the class with member functions written as out-line functions. every function must begin with a template prefix the class name is the generic name Box

Static Members of a Class Template A template class can have static data members and static functions. When a data member is declared as static, each class instantiated from the class template has its own copy of the static data member.

template class Box { private: T dataMember; static int refCount; public: Box (const T& data); void display ( ); }; template int Box ::refCount = 5; declaration of a static data member initializing a static data member.

Templates and Inheritance You can create a class template that derives from a non-template base class. You can create a class that derives from a production of a class template. You can create a class template that inherits from another class template.

class Template from base class class Base {... } template class Derived : public Base {... }

Class from Class Template Production template class Base {... } class Derived : public Base {... } note that you must pick a specific production of the class template Base

Class Template from Class Template template class Base {... } template class Derived : public Base {... } In this case, we inherit from the generalized class template.

Template Parameters Class Templates are often called parameterized classes because the compiler generates code based on the data type used in the actual creation of an object. A template parameter may be A type parameter a non-type parameter another template template template class z>

Code Structure The implementations of functions defined for a class template must be included in the same file (the.h file) as the class definition. Otherwise, the code will not link correctly.

The Standard Template Library The C++ Language comes with a library of standardized container classes known as the Standard Template Library (STL). The basic container classes in the STL are: vector deque list set map

To learn a lot more about templates Take CS 3370, “C++ Software Development”