1Genericity  C++ Templates. 2 Parametric Polymorphism Allows definitions to be parametrized at compile-time Such a definition is actually a “function”

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
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.
Programming Languages and Paradigms The C Programming Language.
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
Generic programming in Java
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.
Type Checking.
OOP Etgar 2008 – Recitation 51 Object Oriented Programming Etgar 2008 Recitation 5.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
1 Parametric Polymorphism  Polymorphism Techniques  C++ Templates.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
Templates. Class templates – why? Writing programs we often use abstract data types such as stack, queue or tree. Implementations of these types may be.
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.
1 CSC241: Object Oriented Programming Lecture No 07.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Intro to Generic Programming Templates and Vectors.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Chapter Nine: Subprograms Lesson 09. What are they  Modularized code  Might return a value  Functions  Or not  Procedures  Subroutines  In object.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
CNS  Executive Overview  Template Parameters  Function Template Issues 2 CNS 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 =
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
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.
Overview of C++ Templates
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
Overview of C++ Polymorphism
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.
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.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
MAITRAYEE MUKERJI Object Oriented Programming in C++
5th MaCS Debrecen On the Turing-Completeness of Generative Metaprograms Zoltán Porkoláb, István Zólyomi Dept. of Programming.
Motivation for Generic Programming in C++
C++ Lesson 1.
Programming with ANSI C ++
Review: Two Programming Paradigms
CS212: Object Oriented Analysis and Design
Templates.
Pointers, Dynamic Data, and Reference Types
CSC 533: Programming Languages Spring 2015
Abstraction: Generic Programming, pt. 2
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Overview of C++ Polymorphism
Templates An introduction.
Templates CMSC 202, Version 4/02.
CSC 533: Programming Languages Spring 2018
Pointers, Dynamic Data, and Reference Types
CSC 533: Programming Languages Spring 2019
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

1Genericity  C++ Templates

2 Parametric Polymorphism Allows definitions to be parametrized at compile-time Such a definition is actually a “function” that returns a new program element(method, class, etc.) Template parameters = The arguments of this “function” AKA: type parameters Instantiation of a template == evaluating the “function”

3 Template Instantiation in C++ The compiler recompiles the template definition Substitutes the formal template parameters with the actual parameters Generates new object code Almost no compilation when the definition is read Most compilation work is at each instantiation point The template definition must be part of the source code That is: #included from an.h file Supporting separate compilation of templates is too difficult in practice

4 C++ Function Templates A function can have type parameters template T* create() { return new T(); } void f() { string* sp = create (); } we use create() thru explicit instantiation We specify the actual types inside a pair of In some cases the compiler can deduce the template parameters template void print(T& t) { cout << t << endl; } void g() { print(5); } We use print() thru implicit instantiation Possible if a type parameter is also a value parameter Make overload resolution more difficult Introduced later

5 C++ Class Templates template class Stack { Type buff[50]; int sp; public: Stack(void): sp(0) {} void push(const Type &e) { buff[sp++] = e; } Type pop(void) { return buff[--sp]; } int empty(void) const { return sp == 0;} int full(void) const{ return sp == 50; } }; template Stack ::push(T val){ if (sp >= size) { error("Stack is full"); return; } buff[sp++] = val; }

6 Kind of Parameters Generics are “routines executed at compile time and produce source code”. Therefore, all parameters must be entities that are known at compile time.  Type: most frequent and most important. All languages which support genericity allow type parameter.  Numerical Constant: e.g., the integer constant 3. Useful for building generic arrays.  Variables: Constant: Address of a variable in C++  Routine: Constant: Address of function in C++

7 A Template Taking a Constant template struct FixedArray { double values[N]; int size() { return N; } // Could be static }; int main(int, char**) { FixedArray arr; arr.values[0] = 3.14; cout << "first element=" << arr.values[0] << endl; cout << "size=" << arr.size() << endl; return 0; }

8 A Template Taking a Function Pointer typedef void (*ErrorFunction)(const char *); template class Array { size_t n; Type *buff; public: Array(size_t n_): n(n_), buff(new Type[n]){ if ((buff == (Type *)0) error("Memory failure"); } Type & operator [] (size_t i) { if (i >= n){ error("Array overflow"); return buff[i]; } }... };

9 Using Function Arguments to Templates #include void err_abort(const char *msg) { cerr << "Error: " << msg <<". Aborting!\n"; exit(1); } typedef Array SafeIntArray;... SafeIntArray a(20);

10 String Arguments to Templates? template class NamedType: public Type { public: const char *name() { return Name; } }; #define NAMED(T) NamedType typedef NAMED(MyClass) MyNamedClass; Does not work! Consider const char *const Hello1 = "Hello"; const char *const Hello2 = "Hello"; Then, Hello1 and Hello2 are not (usually) the same!

11 A Template Taking a Type template struct Pair { void set(const T& x, const T& y) { a = x; b = y; } void print() { cout << a << "," << b << endl; } private: T a, b; }; typedef Pair StrPair; // Instantiate Pair, // pass char* as an argument typedef Pair IntPair; int main(int, char**) { StrPair sp; IntPair ip; sp.set("ab", "cd"); sp.print(); ip.set(10, 20); ip.print(); return 0; }

12Specialization template struct Pair { void set(const T& x, const T& y) { a = x; b = y; } void print() { cout << a << "," << b << endl; } private: T a, b; }; template<> struct Pair { void set(bool x, bool y) { v = (x?1:0) + (y?2:0); } void print() { cout << (v&1) << "," << (v&2) << endl; } private: int v; }; int main(int, char**) { Pair pb; pb.set(true, false); pb.print(); Pair pc; pc.set('x', 'y'); pc.print(); return 0; }

13 A Non Conforming Specialization is Legal template struct Pair { void set(const T& x, const T& y) { a = x; b = y; } void print() { cout << a << "," << b << endl; } private: T a, b; }; template<> struct Pair { void set(bool x, bool y) { v = (x?1:0) + (y?2:0); } public: int v; }; void doSomething() { Pair pb; pb.set(true, false); cout << pb.v << endl; Pair pc; pc.set('x', 'y'); pc.print(); pb.print(); // Error. Pair ::print() is undefined }

14 C++ Templates: Interim Summary A template is a “function” Arguments: types, constants Return value : A new class or a new function Recognized by the compiler The template is recompiled with each Instantiation Specialization == “if” Different result based on the actual arguments

15 Compile Time Computations template struct Factorial { enum { value = N * Factorial ::value }; }; template <> struct Factorial { enum { value = 1 }; }; void foo() { int x = Factorial ::value; // == 24 int y = Factorial ::value; // == 1 }

16 A Non-Terminating Compilation template struct Loop { typedef typename Loop >::Temp Temp; }; int main(int, char**) { Loop n; return 0; }

17 Constraints on Parameters? Constant parameters: type of argument. In C++, the usual type conversions are allowed, e.g., if formal parameter to class template is of type T*, then actual parameter can be of type T1*, provided that T1 is derived from T. Type of parameters: what is the type of a type? Main approaches: No restrictions Dynamic checking Explicit list of constraints By derivation

18 No Restriction on Arguments Any type is allowed. Generic limited to what can be done on all types. Example: Early versions of Eiffel. Advantages: Code sharing. Disadvantages: Restrictions on generics. Only the most primitive operations are allowed on arguments.

19 Dynamic Checking of Arguments (The generic equivalent of dynamic typing.) The compiler tries to instantiate a template. If an invalid operation is attempted, then an error message is issued. Example: C++ Advantages: Compiler writing is easy Flexibility to programmer Disadvantages: Extra burden on the library designer Surprises to the user Constraints are dependent on actual usage Difficult to understand Some parts of static type checking are deferred to link time

20 Explicit List of Constraints The programmer specifies the set of operations that might be used on a type argument. Example: Ada Advantages: Readability No surprises Disadvantages: Lists could be very long Less flexibility in the design of classes List of operations instead of abstraction of functionality

21 Constraints on Type Parameters (cont.) By derivation. The actual parameter must be the same or inherited from the declared type. Example: Current Eiffel Advantages: Code sharing OOP Like Abstraction at the right level Disadvantages: Could lead to over use of inheritance Inheritance is used for abstraction, not only for subtyping Too specific parameter types Too general parameter types Not appropriate for built-in types

22 Quiz: What are the 6 Constraints? template T avg(const T a[], int size) { T sum = a[0]; for (int i = 1; i < size; i++) sum += a[i]; return sum/size; }

23 Quiz: The 5 Constraints template class Stack { Type buff[50]; int sp; public: Stack(void): sp(0) {} void push(const Type &e) { buff[sp++] = e; } Type pop(void) { return buff[--sp]; } int empty(void) const { return sp == 0; } int full(void) const { return sp == 50; } };

24Instantiation Implicit: Instantiation occurs whenever an instance is required. Examples: ML, Function Templates in C++. Advantages: simple syntax. Disadvantages: Surprises. Requires a complex type inference engine: can be in some conditions an undecidable problem. Implicit Usage: Instantiation occurs whenever the programmer uses an instance of a generic for the first time. Examples: Class templates in C++. Optional in function templates in C++ (since November 1993). Advantages: Balance between convenience and accuracy. Disadvantages: Confusing error messages. Relatively complex syntax. Obscure environment of instantiation. Explicit: Programmer must instantiate a generic priorly to using it. Examples: Ada. C++ new features: explicit instantiation. Advantages: Explicit. No surprises. Disadvantages: What if the same generic is instantiated twice?

25 Example: Function Template Instantiation template T max(T a,T b) { return a > b ? a : b; } int main() { extern int f(int); int i(10), j = f(i); int k = max(i, j); extern double cos(double); double r(0.5), s(cos(r)); double t = max(r, s); return max(k, int(1/t)); }

26 Function Return Type? The function return type is not used for resolving ambiguities template inline long double sum(const T a[], int size){ return (long double) avg(a, size) * size; } template inline T sum(const T a[], int size) { return avg(a, size) * size; } The compiler will complain if the sum template is used

27 Class Template Instantiation Whenever a new particular version of the class template Stack is used (such as Stack or Stack ), the compiler will arrange for a version of that template to be instantiated. Each instantiation of template class is a class by itself. The template classes Stack, Stack, and Stack are different classes. There may be compile time errors when a template is instantiated. Only the members that are used should be instantiated. In a single compilation unit, instantiation of a template occurs only once for each particular set of values of the arguments.

28 Explicit Instantiation in C++ New feature: adopted in San Jose, November Ability to specify environment for instantiation. Pre-create libraries of instantiations. Independent of changes in the environment of the using programs. Some implementations: multiple explicit instantiation may produce an error message or warning. Explicit instantiation of a class template: forces instantiation of all its members, whereby forcing constraints. template class Stack ; Explicit instantiation of a function member of a class template: template void Stack ::push(int &);... Explicit instantiation of a function template:...

29 Explicit Instantiation of Function Template Given the function template: template T max(T a, T b) { return a > b ? a : b; } Explicit Instantiation is: template int max (int, int); // naming the argument template int max(int, int); // the argument is deduced here