advanced programming n.
Skip this Video
Loading SlideShow in 5 Seconds..
Advanced Programming PowerPoint Presentation
Download Presentation
Advanced Programming

Loading in 2 Seconds...

play fullscreen
1 / 101

Advanced Programming - PowerPoint PPT Presentation

  • Uploaded on

Advanced Programming. Rabie A. Ramadan Lecture 6. Templates . A feature of the C++ programming language that allow functions and classes to operate with generic types

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Advanced Programming' - oshin

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
advanced programming

Advanced Programming

Rabie A. Ramadan

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.

function templates
Behaves like a function that can accept arguments of many different types.

A function template represents a family of functions.

Function Templates
function templates declaration
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.

class template instantiation
More examples on templates :

Class Template Instantiation
templates vs macros
#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
how does a compiler handle a macro
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?
why should that be a problem
The following code compiles without any problem:

you probably expect the output of this program to be:

Why should that be a problem?
why should that be a problem1
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?
other things
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:

Other things
templates vs void pointers
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 and collection classes
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
const vs static
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
how to restrict an application from running multiple instance
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

another method to restrict using multiple instances form a class
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
first part of next time assignment
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
c standard libraries
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


There are features allow you to write programs that work with different languages and number formats ,…

POSIX C standard internationalization API

C++ Standard Libraries
c standard libraries1
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.


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
c standard libraries2
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.




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

containers iterators algorithms
Algorithms use iterators to interact with objects stored in containersContainers, Iterators, Algorithms










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

sequence 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
sequence containers1
<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
associative 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


Associative Containers
associative containers1
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
generic programming example
double sum(double *array, int n) { double s = 0; for (int i = 0; i < n; ++i) s = s + array[i]; return s;}


Elements of type double.

Elements in an array.

Generic Programming Example
generic programming example1
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;}


Elements in an array.

Elements must support addition.

Elements must support conversion from int.

0 is zero.

Elements support assignment.

Generic Programming Example
generic programming example2
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;}


Iterator is indexable.

Generic Programming Example
generic programming example3
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;}


Iterator has * and ++.

Generic Programming Example
generic programming example4
template <class InputIter, class T>T sum(InputIter begin, InputIter end, T s) { while (begin != end) s = s + *begin++; return s;}


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.

input iterator
Input only

Can be advanced

What can we do with this?


Input Iterator
input iterator1

== must be defined as equality test

Each runs in constant time

Input Iterator
output iterator
Can be used to “write”.

Cannot be used to “read”.

There is no requirements for == and !=

Output Iterator
forward 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?

bidirectional iterators
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
random access iterator binary search algorithm
We look for the middle element

Either you search the first half or the second half

Takes O(log N) provided that the access to the middle element must be a constant time operation.

Random Access iterator binary_search Algorithm
hierarchy of iterator concepts
Hierarchy of Iterator Concepts

Input Iterator

Output Iterator

Forward Iterator

Bidirectional Iterator

Random Access Iterator


insert iterator1
It allows the expansion of the sequence / container

Example (copy would not work)

Insert will expand the vector

Insert iterator
container efficiency
Overhead is approx. per-element size in bytes

C/N indicates best /worst case times

C means constant

how stl differs from other libraries

In traditional Libraries , Algorithms are associated with specific class

STL is open; it allows the programmers to design their own algorithms to work on any class

How STL Differs from Other Libraries
how stl differs from other libraries1
Component exchangeability

Algorithms can work with different containers

How STL Differs from Other Libraries
This part is a summary of the first four chapters of the book

Brain W. Kernighan , STL Tutorial and Reference Guide, 2nd Edition, Addison Wesley

You can read the singleton design pattern from

Professional C++ book by Nicholas A. Solter and Scott J. Kleper

You need to go deeply for more examples and understanding

before jdk 5
ArrayList files = new ArrayList();

. . .

String filename = (String) names.get(0);

Moreover, there is no error checking. You can add values of any class:

files.add(new File(". . ."));

This call compiles and runs without error. Elsewhere, casting the result of get to a String will cause an error.

Before JDK 5
jdk 5
Offers type parameters.

The ArrayList class now has a type parameter that indicates the element type:

ArrayList<String> files = new ArrayList<String>();

Readable class declaration

No cast is required for calling get. The compiler knows that the return type is String, not Object:

String filename = files.get(0);

The compiler also knows that the add method of an ArrayList<String> has a parameter of type String.

files.add(new File(". . .")); // can only add String objects to an


definition of a simple generic class
Definition of a Simple Generic Class

The Pair class introduces a type variable T

java generics are type checked
C++: Link and see if all operations can be resolved

Java: Type check and compile generics w/o linking

This requires programmer to give information about type parameter

Java generics are type checked
generic methods
The type variables are inserted after the modifiers (public static, in our case) and before the return type.

To call it either

Or , since the complier will do the type check .

Generic Methods
bounds for type variables
What might do wrong with this code?

The variable smallest has type T, which means that it could be an object of an arbitrary class. How do we know that the class to which T belongs has a compareTo method?

Bounds for Type Variables
bounds for type variables solution
Give a bound for the type variable T:

public static <T extends Comparable> T min(T[] a) . . .

Bounds for Type VariablesSolution
bounded parameterized types
Java allows multiple inheritance in the form of implementing multiple interfaces, so multiple bounds may be necessary to specify a type parameter. The following syntax is used then:

<T extends A & B & C & …>


interface A {…}

interface B {…}

class MultiBounds<T extends A & B> {


Bounded Parameterized Types
generics and subtyping
Is the following code snippet legal?

List<String> ls = new ArrayList<String>(); //1

List<Object> lo = ls; //2

Line 1 is certainly legal. What about line 2? Is a List of Strings a List of Object. Intuitive answer for most is “sure!”. But wait!

The following code (if line 2 were allowed) would attempt to assign an Object to a String!

lo.add(new Object()); // 3

String s = ls.get(0); // 4:

Generics and Subtyping
generic advantages

Extensibility is one of the requirements of any code in general

Generic Advantages
the main idea of generic is extensibility
As much as possible, make your code closed for modification but open for extension

“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”

When you use wrapper code to extend your core functionality and you don’t need to modify that core functionality, you are essentially decorating the code.

The main idea of Generic is Extensibility
the problem
You are writing a program to a company ; the manager asked you to print the specification of a computer ad :

“You get a computer”

After a while he asked to add a Disk to the description

After a while he asked to add a Monitor to the description

After a while he asked to add a CD-ROM to the description

Your option is to go back every time to the original description function or

Using a Wrappers idea to satisfy the Manger’s request

The problem
what was that
It is one of the design patterns named

“Decorator Design pattern”

Your role :

Use a generic options to generate a comparison class that have Max , Min, Avg, Sum, and Multiply on two numbers . Apply the decoration design pattern

What was that?
restrictions and limitations
Type Parameters Cannot Be Instantiated with Primitive Types:

Pair <double > not allowed but Pari <Double> is allowed

You Cannot Throw or Catch Instances of a Generic Class: (the compiler will not accept it )

Restrictions and Limitations
what is wrong with code1
What is wrong with code?

Nothing wrong, it is ok to use type variables in exception specifications