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 =

Slides:



Advertisements
Similar presentations
Constructors and Destructors. Constructor Constructor—what’s this? Constructor—what’s this? method used for initializing objects (of certain class) method.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
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.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
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.
EEL 3801 Part VIII Fundamentals of C and C++ Programming Template Functions and Classes.
The Structure of a C++ Program. Outline 1. Separate Compilation 2. The # Preprocessor 3. Declarations and Definitions 4. Organizing Decls & Defs into.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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.
1 CSC241: Object Oriented Programming Lecture No 25.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
THE PREPROCESSOR
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 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
 2006 Pearson Education, Inc. All rights reserved Templates.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
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(
CS 2304: Templates And Compilation
Programming with ANSI C ++
C++ Templates.
Templates.
Suppose we want to print out the word MISSISSIPPI in big letters.
CS212: Object Oriented Analysis and Design
Templates.
The dirty secrets of objects
Java Programming Language
FUNCTIONS& FUNCTIONS OVERLOADING
CMSC 202 Templates.
CMSC 202 Lesson 22 Templates I.
Abstraction: Generic Programming, pt. 2
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CISC/CMPE320 - Prof. McLeod
Templates I CMSC 202.
Java Programming Language
Lab4 problems More about templates Some STL
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
C++ Templates An Introduction to Generic Programming.
Templates An introduction.
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Templates CMSC 202, Version 4/02.
COP 3330 Object-oriented Programming in C++
Corresponds with Chapter 5
Presentation transcript:

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 = 0; cout << max(x, ++x); // prints 1 cout << x; // prints 1 string s = “hello”; string t = “world”; cout << max(s, t); // prints “world” }

What’s all this? Templates have ugly syntax. Get used to it, and on an exam, be able to “get in the ballpark” of the correct syntax. Conceptually, templates are a lot like macros, just without the unpleasant side effects. –When you see a template, or use a template, think “text substitution” and you’ll be close

Template Instantiation A template definition is a recipe that the compiler can use to generate a function (or a class, more on that later) The compiler will not use this recipe unless/until you instantiate the template. –At that point, the compiler goes and performs the text substitution you asked for, and then compiles the newly generated function as if you’d written that function yourself. What happens if I instantiate the same template multiple different ways? –Well, with function overloading, we just get two or more functions with the same name, but with different arguments!

Example (template definition) template T max(T x, T y) { if (x < y) { return y; } else { return x; } } “T” is the template parameter. Since the “T” is specified as a “typename” (i.e., the name of some type), then “T” can be replaced by any type (e.g., “int” or “string”). T can NOT be replaced by any arbitrary text, just by a type. We have “defined” this template, which means the compiler now knows the recipe. But there is no machine code for the max function yet. The compiler won’t actually compile the max function until we instantiate it. –The compiler does do some preliminary syntax checking, so you can get compiler errors in your template definitions even if you don’t instantiate them.

Example (instantiations) int main(void) { int x = 3; x = max(x, 5); // instantiation #1 double y = max(1.0, 5.0); // instantitation #2 y = max(y, y + 1); // not a new instantiation y = max(x, y); // uh oh! Ambiguous y = max (x, y); // OK, the choice for T is explicitly “double” } For the first instantiation, the compiler can easily guess that “T” should be “int” For the second instantiation, it is also obvious that “T” should be “double” (floating point constants are double) The compiler instantiates a different version of the template for each distinct binding of T that you use (i.e., one time for int one time for double), not each time you call the function. Since both arguments to max are supposed to be the same type (T), the compiler can’t figure out what to do with the ambiguous line, should T be int (convert y) or should T be double (convert x). We can remove the ambiguity in a few ways, the most certain is to simply tell the compiler what argument you want for the “type paremeter” T.

Template Classes C++ also provides template classes. Virtually any “data structure” (AKA “collection”, AKA “container”) will be implemented in C++ as a template –The type of data stored in the structure is really not at all relevant to the data structure itself. Template classes get “defined” and “instantiated” in analogous ways to template functions with the following caveats –The compiler will never guess at the template argument for a template class, you must always explicitly tell the compiler “what T is”. –Classes cannot be “overloaded”, but the compiler will permit you to instantiate the same template class in multiple ways. Each distinct instantiation results in a completely distinct class! (with its own copy of the static data members, for example). –The member functions in a template class are template functions (oh, how confusing!)

An example template class Foo { T x; static int count; public: Foo() { x = 0; count += 1; } T getX(void) { return x; } int howMany(void) { return count; } }; template int Foo ::count = 0; int main(void) { Foo a; cout << a.getX() << endl; // prints 0 Foo b; cout << b.count() << endl; // prints 2 Foo c; cout << c.count() << endl; // prints 1 }

A Useful Example (abridged) template class vector { public: void push_back(T); void pop_back(void); T& operator[](int k); explicit vector(int initial_capacity=8); private: T* data; int length; int capacity; void expand(void); // increase capacity };

Member functions are template functions, ugh. template vector ::vector(int init_cap) { capacity = init_cap; data = new T[capacity]; length = 0; } template void vector ::push_back(T x) { if (capacity == length) { expand(); } data[length] = x; length += 1; } template void vector ::expand(void) { capacity *= 2; T* new_data = new T[capacity]; for (int k = 0; k < length; k += 1) { new_data[k] = data[k]; } delete[] data; data = new_data; }

Templates and.h files C++ programs (just like C) are intended to be “separately compiled”. –Each module can be compiled independently and then linked together at the end to form the executable program. –This is nice for large development teams. Type definitions and function declarations that are “public” (i.e., used by more than one module in the system) are usually placed into a.h file –Any module that needs to know about these functions or types simply #includes the.h file. –When that module is compiled, the compiler checks the syntax by which you are calling those functions, but the compiler doesn’t actually generate machine code for those functions – i.e., the compiler uses the.h file just to make sure the modules will “interoperate”. BUT templates require that the compiler instantiate them (or else there’s no machine code to interoperate with). And the compiler won’t know which templates to instantiate (or how to instantiate them) until it looks at all the other modules in the project. –In practice this means that the entire template (not just declarations) must be placed into the.h file. –If you’re writing a template class, you might consider just accepting this, and expanding all your member functions in place (inside the class definition).