Templates An introduction.

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

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.
Intro to Generic Programming Templates and Vectors.
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.
EEL 3801 Part VIII Fundamentals of C and C++ Programming Template Functions and Classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
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 =
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.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
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.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
C++ Functions A bit of review (things we’ve covered so far)
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(
Memory Management.
Operator Overloading Introduction
Motivation for Generic Programming in C++
CS 2304: Templates And Compilation
Programming with ANSI C ++
C++ Templates.
Templates.
Suppose we want to print out the word MISSISSIPPI in big letters.
Lecture 6 : Template Acknowledgement : courtesy of Prof. Dekai Wu lecture slides.
Chapter 14 Templates C++ How to Program, 8/e
Review: Two Programming Paradigms
CS212: Object Oriented Analysis and Design
Templates.
The dirty secrets of objects
Templates in C++.
CSC240 Computer Science III
Separate Compilation and Namespaces
Java Programming Language
FUNCTIONS& FUNCTIONS OVERLOADING
Name: Rubaisha Rajpoot
Pointers, Dynamic Data, and Reference Types
CMSC 202 Templates.
CMSC 202 Lesson 22 Templates I.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Constructors and Other Tools
Abstraction: Generic Programming, pt. 2
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CISC/CMPE320 - Prof. McLeod
C++ Templates CSE 333 Summer 2018
Parasol Lab, Texas A&M University
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 Generic Programming.
Function Templates Class Templates
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++
Lecture 3 More on Flow Control, More on Functions,
Corresponds with Chapter 5
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Templates An introduction

Simple Template Functions template <typename T> 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 <typename T, typename U> 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<double>(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 <typename T> class Foo { T x; static int count; public: Foo() { x = 0; count += 1; } T getX(void) { return x; } int howMany(void) { return count; } }; int Foo<T>::count = 0; int main(void) { Foo<int> a; cout << a.getX() << endl; // prints 0 Foo<int> b; cout << b.count() << endl; // prints 2 Foo<double> c; cout << c.count() << endl; // prints 1

A Useful Example (abridged) template <typename T> 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 <typename T> vector<T>::vector(int init_cap) { capacity = init_cap; data = new T[capacity]; length = 0; } void vector<T>::push_back(T x) { if (capacity == length) { expand(); } data[length] = x; length += 1; void vector<T>::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).