1.02k likes | 1.21k Views
Advanced Programming. Rabie A. Ramadan Rabie@rabieramadan.org http://www.rabieramadan.org/classes/2011//Advpro/ Lecture 6. Templates . A feature of the C++ programming language that allow functions and classes to operate with generic types
E N D
Advanced Programming Rabie A. Ramadan Rabie@rabieramadan.org http://www.rabieramadan.org/classes/2011//Advpro/ Lecture 6
A feature of the C++ programming language that allow functions and classes to operate with generic types Allows a function or class to work on many different data types without being rewritten for each one. A mold from which the compiler generates a family of classes or functions. Templates
Behaves like a function that can accept arguments of many different types. A function template represents a family of functions. Function Templates
template <typename T> Indicates that T is a template parameter Equivalent to template <class T> Variables declared with ‘const’ added become constants and cannot be altered by the program. Helps in error messages Which one is constant , the pointer or the variable ? const int * Constant2; int const * Constant2; int * const Constant3; int const * const Constant4; Function Templates declaration
const int * Constant2 ; Declares that Constant2 is variable pointer to a constant integer int const * Constant2; An alternative syntax which does the same, int * const Constant3 Declares that Constant3 is constant pointer to a variable integer int const * const Constant4 Declares that Constant4 is constant pointer to a constant integer. const
Members of templated classes are defined differently than those of nontemplated classes. Members of Class Templates
More examples on templates : http://www.josuttis.com/tmplbook/toc.html Class Template Instantiation
#define SquareOf(x) x*x It defines a kind of functionwhich, used in an actual piece of code, Looks exactly like any other function call: double yout,xin=3; yout = SquareOf(xin); The formal syntax of a macro is: #define name(dummy1[,dummy2][,...]) tokenstring Templatesvs. Macros
It gets handled and done with at compilation time rather than at run time. When the compiler encounters a previously defined macro, it first isolates its actual arguments, handling them as plain text strings separated by commas. It then parses the tokenstring, isolates all occurrences of each dummy-argument symbol and replaces it by the actual argument string. The whole process consists entirely of mechanical string substitutions with almost no semantic testing! How does a compiler handle a macro?
The following code compiles without any problem: you probably expect the output of this program to be: Why should that be a problem?
What you actually get, however, is this: What happened? When the compiler met the string "SquareOf(xin+4)", it replaced it with the string "x*x" and then replaced each of the dummy-argument-strings "x" by the actual-argument-string "xin+4", obtaining the final string "xin+4*xin+4" which, in fact, evaluates to 19 and not to the expected 49. ? Why should that be a problem?
compilers ignore macros until they are invoked. If macro A(...) contains a call to macro B(...) there is no reason for the definitions of the two macros to appear in any particular order. If the definitions are in a header file, that of macro A may precede the one of macro B. It is only important that both macros be defined when macro A is actually called. On the other hand, when a macro is never invoked, its definition is completely irrelevant. Your header file may therefore contain nonsensical definitions of a number of unused macros and you will not find out until, at some later revision, you actually invoke one of them! Other problems could be found here: http://www.ebyte.it/library/codesnippets/WritingCppMacros.html Other things
Void pointers are often used to allow functions to operate on data of an unknown type. to use it you just have to cast it to another kind of pointer first. When using void pointers, the compiler cannot distinguish types, so it cannot perform type checking. Templates vs. Void Pointers
Templates are a good way of implementing collection classes. Microsoft Foundation Class (MFC) Library uses templates to implement some collection classes: CArray, CMap, and CList, Templates and Collection Classes
What is the difference between constant and static ? “const” cannot be altered by the program “static” I have only one instance Why do I need to use static ? Some of the programs requires only one instance such as “A Logging Mechanism” A class that is responsible for writing status information, debugging data, and errors to a central location. The ideal logging class has the following characteristics: It is available at all times. It is easy to use. It provides a set of useful features. const Vs. static
Let’s say “A Logging Mechanism” makes it easier to use because you never have to worry about which logger is the current one or how to get a hold of the current logger. Simply , Use static methods How to restrict an application from running multiple instance ?
Everything is a static Even , the constructor is private
static : Restricts multiple copies Instead : Use control statements such as checking if multiple instance is used or not Simple method is to use static variable to count the number of instances. This is what s called “Singleton Design Pattern” Another method to restrict using multiple instances form a class
Convert the logger class into template class Implement the task “Task scheduler” using C++ and log every detail of the application. Use the concept of “ singleton design pattern” to restrict multiple instances of the “logger class” Use the “static” and “control” concepts to satisfy the singleton design pattern requirements. Assignment is posted on the website First Part of next time assignment
Any standard compiler should include it You may assume that they are part of the core language String Class Superior class in every way Is a template class I/O Stream A model for I/O without a type Based on a template Internationalization There are features allow you to write programs that work with different languages and number formats ,… POSIX C standard internationalization API C++ Standard Libraries
Smart Pointers There is a limited smart pointer template , called the auto_ptr Allows you wrap a pointer of any type such that delete is called automatically when it goes out of scope. Exceptions Mathematical Utilities Complex number class complex C++ provides a numeric_limits template class to get the limit of numeric's. The template class describes arithmetic properties of built-in numerical types. C++ Standard Libraries
Standard Template Library (STL) The heart of the C++ libraries Named STL , because it is abundant use of templates Tries to separate algorithms and data structures. Containers Iterators Algorithms Also provides performance guarantees C++ Standard Libraries
A container is a way that stored data is organized in memory, for example an array of elements. Algorithms in the STL are procedures that are applied to containers to process their data, for example search for an element in an array, or sort an array. Iterators are a generalization of the concept of pointers, they point to elements in a container, for example you can increment an iterator to point to the next element in an array STL
Algorithms use iterators to interact with objects stored in containers Containers, Iterators, Algorithms Container Container Iterator Algorithm Iterator Algorithm Iterator Iterator Algorithm
A container is a way to store data, either built-in data types like int and float, or class objects The STL provides several basic kinds of containers <vector> : one-dimensional array <list> : double linked list <deque> : double-ended queue <queue> : queue <stack> : stack <set> : set <map> : associative array Containers
A sequence container stores a set of elements in a sequence, in other words each element (except for the first and last one) is preceded by one specific element and followed by another, <vector>, <list> and <deque> are sequential containers <vector> is an expandable array that can shrink or grow in size, but still has the disadvantage of inserting or deleting elements in the middle Sequence Containers
<list> is a double linked list (each element has points to its successor and predecessor), it is quick to insert or delete elements but has slow random access <deque> is a double-ended queue, that means one can insert and delete elements from both ends, it is a kind of combination between a stack (last in first out) and a queue (first in first out). Sequence Containers
An associative container is non-sequential but uses a key to access elements. The keys, typically a number or a string, are used by the container to arrange the stored elements in a specific order, For example in a dictionary the entries are ordered alphabetically. Associative Containers
A <set> stores a number of items which contain keys The keys are the attributes used to order the items, for example a set might store objects of the class Person which are ordered alphabetically using their names. There is no separate key/value pair but the key is the value itself. A <map> stores pairs of objects: a key object and an associated value object. A <map> is somehow similar to an array except instead of accessing its elements with index numbers, you access them with indices of an arbitrary type. <set> and <map> only allow one key of each value, whereas <multiset> and <multimap> allow multiple identical key values (they allow duplicate objects.) Associative Containers
double sum(double *array, int n) { double s = 0; for (int i = 0; i < n; ++i) s = s + array[i]; return s;} Requirements? Elements of type double. Elements in an array. Generic Programming Example
template <typename T>T sum(T *array, int n) { T s = 0; for (int i = 0; i < n; ++i)s = s + array[i]; return s;} Requirements: Elements in an array. Elements must support addition. Elements must support conversion from int. 0 is zero. Elements support assignment. Generic Programming Example
template <class RandomAccessIter, class T>T sum(RandomAccessIter iter, int n, T s) { for (int i = 0; i < n; ++i)s = s + iter[i]; return s;} Requirements: Iterator is indexable. Generic Programming Example
template <class InputIter, class T>T sum(InputIter start, int n, T s) { for (int i = 0; i < n; ++i) s = s + *start++; return s;} Requirements: Iterator has * and ++. Generic Programming Example
template <class InputIter, class T>T sum(InputIter begin, InputIter end, T s) { while (begin != end) s = s + *begin++; return s;} Requirements: Iterator has !=, *, and ++. Generic Programming Example
What do want to do with an iterator? Advance it. (++) Go backwards. (--) Write to it. (*it = 1) Read from it. (i = *it) Index it. (it[i]) What concepts are there? Input Iterator Output Iterator Forward Iterator Bidirectional Iterator Random Access Iterator Basic idea is that of a pointer. Iterators
Input only Can be advanced What can we do with this? Search/find Input Iterator
Requirements: == must be defined as equality test Each runs in constant time Input Iterator
Can be used to “write”. Cannot be used to “read”. There is no requirements for == and != Output Iterator
It is kind of input and output iterators Support forward direction. Supports multiple passes (algorithms that need iterations). Iterator can be copied. MyIterator it1 = …, it2 = it1;++it1;++it2;it1 == it2; // True? ForwardIterator
ForwardIteratorSTL Replace- other examples With array: With deque :
Forward iterator goes in a single direction Can go both directions. Has to support all forward iterators operations plus -- What can we do with this? Reverse What type of a list that supports reveres operation? Double linked list Bidirectional Iterators