CNS 3370.  Executive Overview  Template Parameters  Function Template Issues 2 CNS 3370 - Templates.

Slides:



Advertisements
Similar presentations
C++ Basics Variables, Identifiers, Assignments, Input/Output.
Advertisements

Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Polymorphism Chapter EightModern Programming Languages1.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
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 Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Subprograms Support process abstraction and modularity –characteristics of subprograms are that they have a single entry point the calling entity is suspended.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
C++ Template Metaprogramming Why, When and How? Zoltán Porkoláb Dept. of Programming Languages and Compilers, Faculty of Informatics Eötvös.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Understanding C++ Templates CNS 3370 Copyright 2006, Fresh Sources, Inc.
Defining New Types Lecture 21 Hartmut Kaiser
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 =
1 C++ Syntax and Semantics, and the Program Development Process.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
GPCE'04, Vancouver 1 Towards a General Template Introspection Library in C++ István Zólyomi, Zoltán Porkoláb Department of Programming Languages and Compilers.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
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.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
March 2006 Copyright, 2006 Oxford Consulting, Ltd C++ Templates Templates F Part of the ongoing development of the C++ language F Integral part.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
 Templates enable us to define generic classes and functions and thus provides support for generic programming. Generic types are used as parameters.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Copyright © Curt Hill Generic Functions Separating Data Type from Logic.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
C++ Functions A bit of review (things we’ve covered so far)
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
CNS  Template Specialization  Member Templates  Template Metaprogramming  Template Idioms  Templates and Friends 2 CNS Templates.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
5th MaCS Debrecen On the Turing-Completeness of Generative Metaprograms Zoltán Porkoláb, István Zólyomi Dept. of Programming.
C++ Lesson 1.
Programming with ANSI C ++
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Student Book An Introduction
CS212: Object Oriented Analysis and Design
Pointers, Dynamic Data, and Reference Types
Abstraction: Generic Programming, pt. 2
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Templates An introduction.
Presentation transcript:

CNS 3370

 Executive Overview  Template Parameters  Function Template Issues 2 CNS Templates

 Generic Programming  Compile-time Code Generation  Implicit Interfaces  Template Terminology 3 CNS Templates

 Not a new idea  Object mega-hierarchy; void* in C  Based on innovations from ML and Ada  Statically-checked  Allows efficient use of built-in types 4 CNS Templates

 aka “Duck Typing”  If it quacks like a duck, … (i.e., it fits the bill :-)  The status quo for dynamically-typed languages  Perl, Python, PHP, Ruby…  C++ statically verifies that generic types support required operations template const T& min(const T& a, const T& b) { return (a < b) ? a : b; } … min(i,j) // T deduced 5 CNS Templates

 Separate code versions are automatically generated  On-demand code generation  Implicit and explicit  Potential for Code Bloat template class Stack { T* data; size_t count; public: void push(const T& t); // etc. }; // Explicit instantiation Stack s; 6 CNS Templates

7

 If using a function template, the requested function definition is instantiated  If using a class template, the requested version of the class definition is instantiated  For the compiler’s use (just like regular classes)  But only the member functions actually used are generated 8 CNS Templates

class X { public: void f() {} }; class Y { public: void g() {} }; template class Z { T t; public: void a() { t.f(); } void b() { t.g(); } }; int main() { Z zx; zx.a(); // Z ::b() not attempted Z zy; zy.b(); // Z ::a() not attempted } Question: When are the names f and g looked up by the compiler? 9 CNS Templates

 Totally in header files  The template code must be available during instantiation  This is the Inclusion Model of template compilation 10 CNS Templates

 Template Parameter  Names inside <>’s after the template keyword ( )  Template Argument  Names inside <>’s in a specialization ( )  Template Specialization  What results when you provide arguments (Stack )  Instantiation  The class or function generated for a complete set of template arguments  An instantiation is always a specialization 11 CNS Templates

 Templates are instructions for compile-time code generation  They enable type-safe, type-transparent code  Template parameters constitute implicit interfaces  “Duck Typing”  Classic OOP uses explicit interfaces and runtime polymorphism  Templates and OOP can complement each other 12 CNS Templates

 3 Kinds…  Type parameters  the most common (vector )  Non-type  compile-time integral values (bitset, for example)  Templates  “template template parameters” 13 CNS Templates

 Container logic is independent of the contained type  template // T is a type parm class vector { T* data; … };  vector v;// int is a type argument 14 CNS Templates

 Must be compile-time constant values  integral expressions (including static addresses)  Often used to place member arrays on the runtime stack  Example: std::array  And std::bitset  see next 3 slides… 15 CNS Templates

 A “replacement” for built-in arrays  a template wrapper that holds a static array  stored on stack  Provides STL-like features:  begin(), end(), size(), empty(), at(), front(), back()  and of course operator[] (not range-checked)  See array.cpp

 Simulates a fixed-size collection of bits  Like numbers, 0 (zero) is the right-most position  Number of bits determined at compile-time  No need for the heap  Array is embedded in the object  Example: bitset.cpp 17 CNS Templates

template class bitset { typedef unsigned int Block; enum {BLKSIZ = CHAR_BIT * sizeof (Block)}; enum {nblks_ = (N+BLKSIZ-1) / BLKSIZ}; Block bits_[nblks_]; // Embedded array … }; 18 CNS Templates

 Like default function arguments  if missing, the defaults are supplied  only allowed in class templates  template class FixedStack { T data[N]; … }; FixedStack<> s1; // = FixedStack s2; // = 19 CNS Templates

 template > class vector;  Note how the second parameter uses the first 20 CNS Templates

 Templates are not types!  They are instructions for generating types  If you plan on using a template parameter itself as a template, the compiler needs to know  Examples follow… 21 CNS Templates

// A simple, expandable sequence (like vector) template class Array { enum { INIT = 10 }; T* data; size_t capacity; size_t count; public: Array() { count = 0; data = new T[capacity = INIT]; } ~Array() { delete [] data; } void push_back(const T& t) {...} void pop_back() {...} T* begin() { return data; } T* end() { return data + count; } }; 22 CNS Templates

template class Seq> class Container { Seq seq; public: void append(const T& t) { seq.push_back(t); } T* begin() { return seq.begin(); } T* end() { return seq.end(); } }; int main() { Container container; // Pass template container.append(1); container.append(2); int* p = container.begin(); while(p != container.end()) cout << *p++ << endl; } 23 CNS Templates

 Type Deduction of Arguments  Function template overloading  Partial Ordering of Function Templates 24 CNS Templates

 The compiler usually deduces type parameters from the arguments in the function call  the corresponding specialization is instantiated automatically  Sometimes it can’t:  when the arguments are different types ( min(1.0, 2) )  when the template argument is a return type 25 CNS Templates

// StringConv.h #include template T fromString(const std::string& s) { std::istringstream is(s); T t; is >> t; return t; } template std::string toString(const T& t) { std::ostringstream s; s << t; return s.str(); } 26 CNS Templates

int main() { // Implicit Type Deduction int i = 1234; cout << "i == \"" << toString(i) << "\"" << endl; float x = ; cout << "x == \"" << toString(x) << "\"" << endl; complex c(1.0, 2.0); cout << "c == \"" << toString(c) << "\"" << endl; cout << endl; // Explicit Function Template Specialization i = fromString (string("1234")); cout << "i == " << i << endl; x = fromString (string("567.89")); cout << "x == " << x << endl; c = fromString >(string("(1.0,2.0)")); cout << "c == " << c << endl; } 27 CNS Templates

 You can define multiple functions and function templates with the same name  The “best match” will be used  You can also overload a function template by having a different number of template parameters 28 CNS Templates

template const T& min(const T& a, const T& b) { return (a < b) ? a : b; } const char* min(const char* a, const char* b) { return (strcmp(a, b) < 0) ? a : b; } double min(double x, double y) { return (x < y) ? x : y; } int main() { const char *s2 = "say \"Ni-!\"", *s1 = "knights who"; cout << min(1, 2) << endl; // 1: 1 (template) cout << min(1.0, 2.0) << endl; // 2: 1 (double) cout << min(1, 2.0) << endl; // 3: 1 (double) cout << min(s1, s2) << endl; // 4: "knights who" // (const char*) cout (s1, s2) << endl; // 5: say "Ni-!" // (template) } CNS Templates 29

 With overloaded function templates, there needs to be a way to choose the “best fit”  Plain functions are always considered better than templates  Everything else being equal  Some templates are better than others also  More “specialized” if matches more combinations of arguments types than another  Example follows 30 CNS Templates

template void f(T) { cout << "T" << endl; } template void f(T*) { cout << "T*" << endl; } template void f(const T*) { cout << "const T*" << endl; } int main() { f(0); // T int i = 0; f(&i); // T* const int j = 0; f(&j); // const T* } CNS Templates 31

 Arguments that can be deduced will be  The rest you must provide  Put those first in the argument list so the others can be deduced by the compiler  Standard Conversions do not apply when using unqualified calls to function templates  Arguments must match parameters exactly  Except const adornments are okay 32 CNS Templates

std::pair, std::tuple CNS Templates33

 Holds a pair of any two types:  pair p1(10,”ten”);  auto p1 = make_pair(10,string(“ten”));  Used to hold the key and value in a map  Retrieve values with first and second  struct data members  See pair.cpp

 Holds an arbitrary number of items  Handy for returning multiple items from a function  Can retrieve by position  with template args (get (tup), etc.)  Can do item-wise assignment  See tuple.cpp