Presentation is loading. Please wait.

Presentation is loading. Please wait.

TEMPLATES Lecture 32-45 Presented By SHERY KHAN Object Orienting Programming.

Similar presentations


Presentation on theme: "TEMPLATES Lecture 32-45 Presented By SHERY KHAN Object Orienting Programming."— Presentation transcript:

1 TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming

2 Agenda Templates Templates User Specialization User Specialization User Define Types User Define Types Class Templates Class Templates Member Templates Member Templates Partial Specialization Partial Specialization Complete Specialization Complete Specialization Non Type Parameters/Default Type Parameter Non Type Parameters/Default Type Parameter Resolution Order/Template & Friends Resolution Order/Template & Friends Template and Static Members Template and Static Members Cursors Cursors Iterator Iterator Standard Template Library Standard Template Library

3 TEMPLATES C++ More Power full Feature,namely Templates. C++ More Power full Feature,namely Templates. Templates Enable Us to specify with single code segments an entire Range of related (overloaded function called TEMPLATE FUNCTION Templates Enable Us to specify with single code segments an entire Range of related (overloaded function called TEMPLATE FUNCTION Or Entire Range of related Classes –Called Template Classes Or Entire Range of related Classes –Called Template Classes Advantages: Advantages: We might write a single Function for any Problem and use it with different Data types :int,float,char,string We might write a single Function for any Problem and use it with different Data types :int,float,char,string

4 Generic Concept Generic Programming refers to program containing generic abstraction Generic Programming refers to program containing generic abstraction If we have same logic like print some numbers whether they have different data types we can draw a Algorithm that is Generic and used with different Data type If we have same logic like print some numbers whether they have different data types we can draw a Algorithm that is Generic and used with different Data type

5 Advantages REUSEABILTY :code can Work for all data type REUSEABILTY :code can Work for all data type Writ ability : Lesser Time to write Writ ability : Lesser Time to write Maintainability: Change in one Function so increase Maintainability Maintainability: Change in one Function so increase Maintainability

6 Distinction B/w Function Template & Template Function Function Templates and class templates are like stencil out of which we trace shapes. Function Templates and class templates are like stencil out of which we trace shapes. Function templates can be parameterized to operate on different data type. Function templates can be parameterized to operate on different data type. Template Function and template classes are like the separate tracing that all have the Same Shapes but could be drawn in different colors Template Function and template classes are like the separate tracing that all have the Same Shapes but could be drawn in different colors

7 FUNCTION TEMPLATES OVERLOADED FUNCTION: OVERLOADED FUNCTION: Are normally used to perform Similar Operation on Different Data Types Are normally used to perform Similar Operation on Different Data Types FUNCTION TEMPLATES: FUNCTION TEMPLATES: If Operation are Identical for Each type this may be performed more compactly and Conveniently using Function Templates If Operation are Identical for Each type this may be performed more compactly and Conveniently using Function Templates

8 continue The programmer writes a Single Function template Definition based on the Arguments provided in calls to this function the complier automatically generate a separate object code function to handle Each type of Call Appropriately The programmer writes a Single Function template Definition based on the Arguments provided in calls to this function the complier automatically generate a separate object code function to handle Each type of Call Appropriately NOTE!!!! NOTE!!!! :::::C this Task was done by Macros but they donot care about Type Checking :::::C this Task was done by Macros but they donot care about Type Checking

9 Declaration Function Template All function Template begin with Keyword template followed by list of Parameters template followed by list of Parameters to function template enclosed in angel brackets template template Or template Or template template template

10 continue In Above Declaration T is type name of class name and we use this T instead of data type for which we want our function to work as template. In Above Declaration T is type name of class name and we use this T instead of data type for which we want our function to work as template.

11 Example Let us examine the pA function template this template is used in Complete program Let us examine the pA function template this template is used in Complete program

12 Program TEMPlATE #include #include template ………………… template ………………… void pA( T *array, int count) void pA( T *array, int count) { for(int i=0;i

13 Program Main part int main() int main() { const int account=5,bcount=4,ccount=6,fcount=3; // Declaring Size of Array const int account=5,bcount=4,ccount=6,fcount=3; // Declaring Size of Array int a[acount]={1,2,3,4,5}; int a[acount]={1,2,3,4,5}; double b[bcount]={1.1, 2.2, 3.3, 4.4}; double b[bcount]={1.1, 2.2, 3.3, 4.4}; float f[fcount]={24.26,56.56, }; float f[fcount]={24.26,56.56, }; char c[ccount]="ABC"; char c[ccount]="ABC"; pA(a,acount); pA(a,acount); pA(b,bcount); pA(b,bcount); pA(c,ccount); pA(c,ccount); pA(f,fcount); pA(f,fcount); system("pause"); system("pause"); }

14 OUT PUT You see for int,double,char,float You see for int,double,char,float one function template is used one function template is used

15 Explicit Type Parameterization: In case the Function template does not have any parameter then we have to explicit mention the data type. In case the Function template does not have any parameter then we have to explicit mention the data type. template int main() T get input() int x; T x; x=getinput (); cin>>x; double y; return x; y=getinput (); Note :x=getinput(); // ERROR !!!! Note :x=getinput(); // ERROR !!!! Explicit data type

16 User Define Specialization A template Compiler Generated code may not handle all the types successfully in this case we give a explicit specialization for particular data type. A template Compiler Generated code may not handle all the types successfully in this case we give a explicit specialization for particular data type. For this purpose we give our own correct specialization code

17 USER SPECIALIZATION Some time our template is cant handle a all data types for this purpose we do user specialization for this appropriate type Some time our template is cant handle a all data types for this purpose we do user specialization for this appropriate type template template bool isEqual( T x,T y) bool isEqual( T x,T y) return(x==y); return(x==y);

18 Failure IsEqual(“abc”,”xyz”) IsEqual(“abc”,”xyz”) This code is fail can return Logical Error !!! Because of our implementation is x==y Complier Translate it is Return (char*==char*) OR return(char[]=char[]); Array consist of many element so comparison of array is not Possible it will simple compare first element

19 What should we do? We do User specialization We do User specialization The code is below Template<> bool isEqual bool isEqual Const char*x,const char*y) { Return (strcmp(x,y)==0); }

20 PAPERS Q: Write the names of two types of Templates. MARKS: 2 Q: Write the names of two types of Templates. MARKS: 2 Answer:- (Page 256) Answer:- (Page 256) a. Function Templates (in case we want to write general function like print Array) a. Function Templates (in case we want to write general function like print Array) b. Class Templates (in case we want to write general class like Array class) b. Class Templates (in case we want to write general class like Array class) Which of the following is the best approach if it is required to have more than one functions having exactly same functionality and implemented on different data types? Which of the following is the best approach if it is required to have more than one functions having exactly same functionality and implemented on different data types? ► Templates (Page 256) ► Templates (Page 256) ► Overloading ► Overloading ► Data hiding ► Data hiding ► Encapsulation ► Encapsulation

21 Multiple Type Argument For Conversion of Int to float or other data type conversion we use two type argument templates advantage is decrease the required no of functions because the only one Generic template is Write and use it for conversion For Conversion of Int to float or other data type conversion we use two type argument templates advantage is decrease the required no of functions because the only one Generic template is Write and use it for conversion

22 Multiple Type Argument Syntax Syntax template template T my_cast(U u){ return(T)u;// U is converted to T type; } Int main(){ Double d = ; Int j=my_cast(d);//Error int i=my_cast d Any Data type you want to convert Need to mention the Type

23 Overloading /Templates Overloading: Similar Operation(Milta Julta) Overloading: Similar Operation(Milta Julta) For E.g : Plus complex, imag Function Template: Identical Operation(Bilkul Aik ha Exactly Same ho) Function Template: Identical Operation(Bilkul Aik ha Exactly Same ho) For E.g. Array implementation for different Data Type we Use Function Template Because they have Same Type For E.g. Array implementation for different Data Type we Use Function Template Because they have Same Type

24 Papers Give the pseudo code of non case sensitive comparison function of string class. Answer:- (Page 263) Give the pseudo code of non case sensitive comparison function of string class. Answer:- (Page 263) int caseSencompare( char* str1, char* str2 ) int caseSencompare( char* str1, char* str2 ) { for (int i = 0; i < strlen( str1 ) && i < strlen( str2 ); ++i) { for (int i = 0; i < strlen( str1 ) && i < strlen( str2 ); ++i) if ( str1[i] != str2[i] ) if ( str1[i] != str2[i] ) return str1[i] - str2[i]; return str1[i] - str2[i]; return strlen(str1) - strlen(str2); } return strlen(str1) - strlen(str2); }

25 Paper What do you know about function Template? What do you know about function Template? (Answer: Page 262) Function templates are used when we want to have exactly identical operations on different data types in case of function templates we cannot change implementation from data type to data type however we can specialize implementation for a particular data type. (Answer: Page 262) Function templates are used when we want to have exactly identical operations on different data types in case of function templates we cannot change implementation from data type to data type however we can specialize implementation for a particular data type.

26 GENERIC ALGORITHM We want a Implementation which is Independent of Data Structure in pA we can print a Array which is work fine for all data Types Using Generic programming Concept but now We want to Implement a Template which is Type and Data Structure Independent So best Generic Algorithm is that which is independent of Both type and Data Structure. We want a Implementation which is Independent of Data Structure in pA we can print a Array which is work fine for all data Types Using Generic programming Concept but now We want to Implement a Template which is Type and Data Structure Independent So best Generic Algorithm is that which is independent of Both type and Data Structure.

27 CASE STUDY CASE STUDY Lecture 34 Lecture 34 Discussion On Type Independence And Discussion On Type Independence And Data Structure Independence

28 Generic Algorithm Independent of Container and Type Independent of Container and Type We have a Find Algorithm Find Simply a Integer from Array we Do Step by Step Operation on it and Explain All Step that Are Done our Purpose is To make a Function Type and data Structure Independent

29 FIND Program (non Generic Funtion) const int* find( const int* array, int _size, int x ) { const int* find( const int* array, int _size, int x ) { const int* p = array; const int* p = array; for (int i = 0; i < _size; i++) { for (int i = 0; i < _size; i++) { if ( *p == x ) if ( *p == x ) return p; return p; p++; p++; } return 0; return 0; }

30 Explanation First Step is To write it as Template so they can Work for All Data Type instead Integers. First Step is To write it as Template so they can Work for All Data Type instead Integers. In Above Code A array has a Parameter passing Named as Find and one Constant Pointer passing and array is Int type and Size tell the How many Elements of Array has and also a int X is passing which is to be Find in Array if x is present in array of Int then return pointer if not return Null Character…… In Above Code A array has a Parameter passing Named as Find and one Constant Pointer passing and array is Int type and Size tell the How many Elements of Array has and also a int X is passing which is to be Find in Array if x is present in array of Int then return pointer if not return Null Character…… Return Type const int* // Return Type const int* // Name of Function Find Name of Function Find Parameter const int*array // Array is Pointer to constant int Parameter const int*array // Array is Pointer to constant int Size of Array : int_size Size of Array : int_size Found Element Int x // As a Third Parameter of Find Function Found Element Int x // As a Third Parameter of Find Function A Temporary pointer is Intailize with Starting Adress of the Array which is passed as parameter A Temporary pointer is Intailize with Starting Adress of the Array which is passed as parameter

31 Type Indepandanant template // Making it Generic So this Notation is Used T* find( T* array,int _size, const T& x ) // Return Type is Changed with T* {T* p = array;for (int i = 0; i < _size; i++) // Local Pointer is intialize toarr {if ( *p == x ) return p; p++;} // pointing to next element of Array used to Go for next Index return 0;} Explaination:First Step is Type Independent Pervious is Int x Is passing as Call by Value but Now we can Passing X as Reference Because we doing it asTypeIndepandant So to avoid Array of Complex we use it Const T & x Because User define data Type are Heavy so in this point we just send reference so it can nt be chaged Array and T* tell us that it is Array first Index Pointer

32 Size is Replaced !!!! template template T* find( T* array, T* beyond, const T& x ) { T* find( T* array, T* beyond, const T& x ) { T* p = array; T* p = array; while ( p != beyond ) { // so by doing this we can just know the Last Element of Container so iteration is from First to last Element so don’t want to know how much size is while ( p != beyond ) { // so by doing this we can just know the Last Element of Container so iteration is from First to last Element so don’t want to know how much size is beyond is pointing to last next Element beyond is pointing to last next Element if ( *p == x ) if ( *p == x ) return p; return p; p++; pass a pointer which is p++; pass a pointer which is } one location next } one location next return 0; After array return 0; After array instead of Passing instead of Passing } Size here in previous we know About Count that how many member of Array Element } Size here in previous we know About Count that how many member of Array Element

33 Return beyound template template T* find( T* array, T* beyond, const T& x ) T* find( T* array, T* beyond, const T& x ) {T* p = array; {T* p = array; while ( p != beyond ) while ( p != beyond ) { if ( *p == x ) By replacing return statement by Beyond so if if ( *p == x ) By replacing return statement by Beyond so if return p; element is not found we will not check return p; element is not found we will not check p++; the return value for Null we simply p++; the return value for Null we simply check whether is pointing to some check whether is pointing to some value or it point to beyond pointer so if Nt Found then pointer points to Beyound value or it point to beyond pointer so if Nt Found then pointer points to Beyound } Null pointer indicate that we using } Null pointer indicate that we using Array because it tells us that All the Array because it tells us that All the return beyond; Array is Iterated so our mission is to return beyond; Array is Iterated so our mission is to Data Structure Independence Data Structure Independence }

34 Single Return Statement template template T* find( T* array, T* beyond, const T& x ) T* find( T* array, T* beyond, const T& x ) { T* p = array; T* p = array; while ( p != beyond && *p != x ) if pointer not go to Array End and Current pointer pointing is not equal to the num which is to be Find check next element otherwise P is pointing to which value is Returned while ( p != beyond && *p != x ) if pointer not go to Array End and Current pointer pointing is not equal to the num which is to be Find check next element otherwise P is pointing to which value is Returned p++; if p find Some point x then it will return otherwise it iterate till then it is pointing to beyound and While false and we return p instead of two returns we have single return code is Simplified Still Not Independent data Structure because the P* exist Array Exist p++; if p find Some point x then it will return otherwise it iterate till then it is pointing to beyound and While false and we return p instead of two returns we have single return code is Simplified Still Not Independent data Structure because the P* exist Array Exist return p; return p; }

35 Generic Code Now our code is so generic that it will work for all types of containers (data structures) supporting two operations, Now our code is so generic that it will work for all types of containers (data structures) supporting two operations, Increment operator (++) as we are incrementing value in this container (Next Element Access) Increment operator (++) as we are incrementing value in this container (Next Element Access) Dereference operator (*) as we are getting value from container for comparison by dereferencing ( Element Access) Dereference operator (*) as we are getting value from container for comparison by dereferencing ( Element Access) Container : is Some Type of Structure Which Contain some Thing it contain one Element and Many Element also Container : is Some Type of Structure Which Contain some Thing it contain one Element and Many Element also Array is one Concrete Example of An Homogenous Container because its all element of Same Type Array is one Concrete Example of An Homogenous Container because its all element of Same Type Vector Vector Queue Queue

36 Limitation that we will need to pass container pointers in this function this is against the concept of generic programming so we simply remove pointer notation from our code, that we will need to pass container pointers in this function this is against the concept of generic programming so we simply remove pointer notation from our code, template template P find( P start, P beyond, const T& x ) //first Element and next to beyond element P find( P start, P beyond, const T& x ) //first Element and next to beyond element { { while ( start != beyond && *start != x )//both referecnce are not Equal we check & start is Dereference // getting Element while ( start != beyond && *start != x )//both referecnce are not Equal we check & start is Dereference // getting Element start++; start++; return start; return start; } That’s Our target by seeing this Code the Underline Data Structure is Not Defined or Independent of underline Data Structure without knowning Data structure we implement it As Array,Queue That’s Our target by seeing this Code the Underline Data Structure is Not Defined or Independent of underline Data Structure without knowning Data structure we implement it As Array,Queue

37 Class Templates A single Class template has a functionality to operate on different data types Reuse of Classes Syntax Syntax template class XYZ{}; or template class XYZ{}; or Template class XYZ{}; Template class XYZ{};

38 Class Template A Vector class template can store data elements of different types, without templates, we need a separate Vector class for each data type. A Vector class template can store data elements of different types, without templates, we need a separate Vector class for each data type. template template class Vector { Tell that it is Parameterized Class which has a private: Parmeter T Not necessary class Vector { Tell that it is Parameterized Class which has a private: Parmeter T Not necessary int size; int size; T* ptr; T* ptr; public: public: Vector ( int = 10 ); //size Vector ( int = 10 ); //size Vector ( const Vector & );// Copy Constructor Vector ( const Vector & );// Copy Constructor ~Vector (); ~Vector (); int getSize() const; int getSize() const; const Vector & operator =( const Vector & operator =( const Vector & ); const Vector & ); T& operator []( int ); T& operator []( int ); }; };

39 INSTANCES We can create this Vector class instance for int or char data type as given We can create this Vector class instance for int or char data type as given Vector intVector Vector intVector Vector charVector Vector charVector Vector Class is Parametrized class and will always be instantiated for particular type only Vector Class is Parametrized class and will always be instantiated for particular type only

40 Papers What is the difference (if any) between the two types of function declarations? What is the difference (if any) between the two types of function declarations? template function_declaration; template function_declaration; Answer:- The format for declaring function templates with type parameters is: Answer:- The format for declaring function templates with type parameters is: template function_ declaration; template function_ declaration; The only difference between both prototypes is the use of either the keyword class or the keyword typename. Its use is indistinct, since both expressions have exactly the same meaning and behave exactly the same way. The only difference between both prototypes is the use of either the keyword class or the keyword typename. Its use is indistinct, since both expressions have exactly the same meaning and behave exactly the same way.

41 MEMBER TEMPLATES A class or class Template can have Member Function that Are Them Selves Member Templates A class or class Template can have Member Function that Are Them Selves Member Templates We say that member function of template class implicitly become Function Template We say that member function of template class implicitly become Function Template They work for Instances (int,char,float,double) They work for Instances (int,char,float,double) Some Situation we Need Explicit Template Function Some Situation we Need Explicit Template Function

42 Continue Some Time We need that class template Member function Explicitly we want for some other type Template (Hum Cha raha hain ka who kisi Aur Type ka liya bhe Type ban Jaye) Some Time We need that class template Member function Explicitly we want for some other type Template (Hum Cha raha hain ka who kisi Aur Type ka liya bhe Type ban Jaye) It mean we Explicitly Member Function to be a Member Template for some Other type which has been given to that Class as a parameter It mean we Explicitly Member Function to be a Member Template for some Other type which has been given to that Class as a parameter

43 Class Template Having Member Function that Are themselves Member Template template class Complex { template class Complex { T real, imag;// Data Member T Type T real, imag;// Data Member T Type public: public: // Complex ( T r, T im ) // Prviously Every Member Function is Parametrized with c++ in Declaration Not used Compler Do it self // Complex ( T r, T im ) // Prviously Every Member Function is Parametrized with c++ in Declaration Not used Compler Do it self Complex( T r, T im ) : // Constructor Taking Two Argument R,im both have Type T parametrized Type Complex( T r, T im ) : // Constructor Taking Two Argument R,im both have Type T parametrized Type real(r), imag(im) {} // Member intializer list we can Intilize the Both the Members real(r), imag(im) {} // Member intializer list we can Intilize the Both the Members // Complex (const Complex & c) // Complex (const Complex & c) Complex(const Complex & c) :// Copy Constructor Rule of thumb that Complex(const Complex & c) :// Copy Constructor Rule of thumb that With name No use of Type But in Return Type or Parameter Fully Qualified name is USed argument of Copy constructor is Const Complex and Reference C With name No use of Type But in Return Type or Parameter Fully Qualified name is USed argument of Copy constructor is Const Complex and Reference C real( c.real ), imag( c.imag ) {} // Intialize Data Member with Member Intializer List real( c.real ), imag( c.imag ) {} // Intialize Data Member with Member Intializer List }; };

44 Main Function int main() { int main() { Complex fc( 0, 0 );// Complex Class is Intantiated for Float argument 0,0 that the real and img part is Set with 0,0 Complex fc( 0, 0 );// Complex Class is Intantiated for Float argument 0,0 that the real and img part is Set with 0,0 Complex dc = fc; // Error Complex dc = fc; // Error // in copy constructor the type is Double and argument which is Send is Float So TYPE MISS MATCH and now there is Need we have a Overloaded Copy Constructor one for double,float,int etc // in copy constructor the type is Double and argument which is Send is Float So TYPE MISS MATCH and now there is Need we have a Overloaded Copy Constructor one for double,float,int etc fc is also a Object of Float which is Initialized with dc object which type is double fc is also a Object of Float which is Initialized with dc object which type is double Here Error because the Complex Float and Complex Double Are two distinct types Complier don’t know about type conversion in class there is no function which tells that How to do conversion Compiler Cant DO Type Conversion Automatically Here Error because the Complex Float and Complex Double Are two distinct types Complier don’t know about type conversion in class there is no function which tells that How to do conversion Compiler Cant DO Type Conversion Automatically return 0; return 0; }

45 Overloaded Copy constructor We need different overloaded copy constructor work is identical Existing object Data member are put and intialize to new data member We need different overloaded copy constructor work is identical Existing object Data member are put and intialize to new data member This Give us a Clue that Copy constructor must be made a Function Template because the parameter is Required type for Complex float,double,etc This Give us a Clue that Copy constructor must be made a Function Template because the parameter is Required type for Complex float,double,etc

46 Double Replaces the T class Complex { class Complex { double real, imag; double real, imag; public: public: Complex( double r, double im ) : Complex( double r, double im ) : real(r), imag(im) {} real(r), imag(im) {} Complex(const Complex & c) : Complex(const Complex & c) : real( c.real ), imag( c.imag ) {} real( c.real ), imag( c.imag ) {} … }; };

47 Member Template template class Complex { template class Complex { T real, imag; T real, imag; public: public: Complex( T r, T im ) : Complex( T r, T im ) : real(r), imag(im) {} real(r), imag(im) {} template template // this copy constructor is now taking two template parameters one implicit T copy constructor is changed Explicitly Member template // this copy constructor is now taking two template parameters one implicit T copy constructor is changed Explicitly Member template U is different Type and T is Different Type They have two Identifiers / parameter types U is different Type and T is Different Type They have two Identifiers / parameter types Complex(const Complex & c) : Complex(const Complex & c) : real( c.real ), imag( c.imag ) {} real( c.real ), imag( c.imag ) {} … }; };

48 Main (ok) Complex fc( 0, 0 );// Complex fc( 0, 0 );// Complex dc = fc;// OKAY FINE Complex dc = fc;// OKAY FINE We are creating a new object in term of another object so compiler know that it is Copy Constructor We are creating a new object in term of another object so compiler know that it is Copy Constructor

49 Now the T replaces as Instantiation Instantiation class Complex { class Complex { double real, imag; double real, imag; public: public: Complex( double r, double im ) : Complex( double r, double im ) : real(r), imag(im) {} real(r), imag(im) {} template template Complex(const Complex & c) : Complex(const Complex & c) : real( c.real ), imag( c.imag ) {} real( c.real ), imag( c.imag ) {} … }; };

50 GooD Complier Only the Required instantiation are done by Compiler not all ……. Only the Required instantiation are done by Compiler not all ……. class Complex { class Complex { float real, imag; float real, imag; public: public: Complex( float r, float im ) : Complex( float r, float im ) : real(r), imag(im) {} real(r), imag(im) {} // No Copy Constructor code is generated as there is no need for it // No Copy Constructor code is generated as there is no need for it … }; };

51 Class Specialization: Like Function Template a class may also not handle all the types successfully so we use Class Specialization Like Function Template a class may also not handle all the types successfully so we use Class Specialization Syntax Syntax template template

52 Class Specialization template template Class Vector { Class Vector { Private: Private: Int size; Int size; Char**ptr;// array to pointers of Character Char**ptr;// array to pointers of Character Public; Public; Vector (int=10); Vector (int=10);

53 Memory Leak Here in code we can dynamically allocate the Memory of Vector so in desructor is called but we know the size of Vector is 10 on Every element of Vector the Pointer is pointing so first we can dsetroy this pointer and then the Vector is Destroy otherwise Memory Leak for this purpose we can Deallocte in this Manner Here in code we can dynamically allocate the Memory of Vector so in desructor is called but we know the size of Vector is 10 on Every element of Vector the Pointer is pointing so first we can dsetroy this pointer and then the Vector is Destroy otherwise Memory Leak for this purpose we can Deallocte in this Manner

54 Destructor template<> template<> Vector ::~Vector(){ Vector ::~Vector(){ For(int i=0;i

55 Non Type Parameter Template Template Here int I is non type Parameter Here int I is non type Parameter They May have Default value They May have Default value Template Template They are Treated as Constant and commonly used in Static Memory Allocation They are Treated as Constant and commonly used in Static Memory Allocation

56 Default Non Type Parameter We can set default values for this non type parameter as we do for parameter passed in ordinary function We can set default values for this non type parameter as we do for parameter passed in ordinary function template template

57 Default Parameter Sytax Sytax template template Class name{ Class name{ } name v; name v;

58 Partial Specialization Partial Specialization of a template provide more information about the type of Template argument than that of template Partial Specialization of a template provide more information about the type of Template argument than that of template Syntax Syntax Vector or Vector or Template or Template or Template Template

59 Continue Similar to Class Template Function Template may Also be partial specialized Similar to Class Template Function Template may Also be partial specialized Syntax Syntax Template Template Void func(T,U,V); Void func(T,U,V);

60 Complete Specialization Syntax Syntax Template Complete Template Complete Class vector{}; Class vector{}; Template<> Template<> Class Vector {}; Class Vector {}; OR OR Template Template

61 RESOLUTION ORDER in Classes Sequence in which a compiler searches for required Template Specialization Sequence in which a compiler searches for required Template Specialization First Of all Look For Complete Specilization First Of all Look For Complete Specilization Then if Com S… not found than Search for Partial Specialization Then if Com S… not found than Search for Partial Specialization In the End it will Search for General Template In the End it will Search for General Template

62 FUNCTION R…O… Ordinary Function Ordinary Function Complete Specialization Complete Specialization Partial Specialization Partial Specialization Generic Template Generic Template

63 Template & Inheritance A Class Template can be derived from a Template Class A Class Template can be derived from a Template Class A class Template can be drived from Non Template A class Template can be drived from Non Template A Template Class can be drived from class Template A Template Class can be drived from class Template A non template class can be drived from a class template A non template class can be drived from a class template

64 Derivation Sytax Sytax Template Template Class A{}; Class A{}; Template Template Class B : public A Class B : public A So a Class Template may Inherit the another class Template So a Class Template may Inherit the another class Template Same Type in both Declaration So they can be Inherited

65 Inheritance continue….. A partial specialization may inherit from class template A partial specialization may inherit from class template Template Template Class B : public A Class B : public A Same Type in both Declaration So they can be Inherited

66 Inheritance continue…. Complete Specialization or Ordinary class cannot inherited from class Template Complete Specialization or Ordinary class cannot inherited from class Template Template Template Class B :public A Class B :public A {}; {}; Class B: publicA Class B: publicA Different Type in both Declaration So they cant be Inherited T is Undefined

67 TEMPLATE & FRIENDS Rule 1: Rule 1: Acc to Rule 1 when an ordinary Function or Class is Declared as Friend of a class template Acc to Rule 1 when an ordinary Function or Class is Declared as Friend of a class template Then it become a friend of each instantiation of that Template class Then it become a friend of each instantiation of that Template class

68 Rule 1: …Example….. class A { class A { … … }; }; template template class B { class B { int data; int data; friend A; // declaring A as friend of B friend A; // declaring A as friend of B … }; }; class A { class A { void method() { void method() { B ib; B ib; B cb B cb ib.data = 5; // OK: Accessing private member ‘data’ for class B instantiation ib ib.data = 5; // OK: Accessing private member ‘data’ for class B instantiation ib cb.data = 6; // OK: Accessing private member ‘data’ for class B instantiation cb cb.data = 6; // OK: Accessing private member ‘data’ for class B instantiation cb } }; };

69 Rule ::::2 when a friend function template or friend class template is instantiated with the type parameters of class template granting friendship then its instantiation for a specific type is a friend of that class template instantiation for that particular type only. when a friend function template or friend class template is instantiated with the type parameters of class template granting friendship then its instantiation for a specific type is a friend of that class template instantiation for that particular type only.

70 RULE 3 When a friend function / class template takes different ‘type parameters’ from the class template granting friendship, then its each instantiation is a friend of each instantiation of the class template granting friendship. Basically here we are removing restriction imposed by Rule 2, due to the use of same type parameter in class B while declaring function doSomething and class A as its friends as shown below, When a friend function / class template takes different ‘type parameters’ from the class template granting friendship, then its each instantiation is a friend of each instantiation of the class template granting friendship. Basically here we are removing restriction imposed by Rule 2, due to the use of same type parameter in class B while declaring function doSomething and class A as its friends as shown below,

71 Pros/cons of Templates Advantages: Advantages: Templates provide Templates provide Reusability Reusability Writability Writability Disadvantages Disadvantages Can consume memory if used without care. Can consume memory if used without care. Templates may affect reliability of a program Templates may affect reliability of a program

72 PAPERS A class template may inherit from another class template. ► True (Page 288) ► False Considering the resolution order in which Considering the resolution order in which compiler search for functions in a program; the first priority is given to; the first priority is given to, ► general template ► partial specialization ► complete specialization ► ordinary function (Page 290)

73 PAPERS Describe the way to declare a template function as a friend of any class. 2marks Answer:- (Page 295) template class B { int data; friend void doSomething( T ); // granting friendship to template doSomething in // class B friend A ; // granting friendship to class A in class B };

74 PAPERS How can we set the default values for non type parameters? Answer:- (Page 286) We can set default value for this non type parameters, as we do for parameters passed in ordinary functions, template class Array { private: T ptr[SIZE]; public: void doSomething(); … }

75 Cursors The cursor is pointer that is used outside the container the following Method help cursor to The cursor is pointer that is used outside the container the following Method help cursor to Traverse the element Traverse the element T* first() // pointing to first Element T* first() // pointing to first Element T* beyond()// last to next T* beyond()// last to next T* next( T* )// current pointer pointing T* next( T* )// current pointer pointing

76 Cursor Cursor is used for contigous sequences Cursor is used for contigous sequences A B C cursor Cursor is not used with non contiguous because when we apply find method on container our find Method Increment operator Fails as element are not placed at next position

77 ITERATORS Iterator is an Object that traverse a Container Iterator is an Object that traverse a Container Iterator are for Container as pointer are for ordinary Array Iterator are for Container as pointer are for ordinary Array For Going to one Element to Other We use Iterators For Going to one Element to Other We use Iterators

78 Generic Iterator A generic iterator Works with any kind of Conatiner to do so a Generic iterator requires its Container to Provide Three Operation A generic iterator Works with any kind of Conatiner to do so a Generic iterator requires its Container to Provide Three Operation T*first() // Pointing to First Element of Container T*first() // Pointing to First Element of Container T*beyond() //one Next to Last T*beyond() //one Next to Last T*next(T*) //gives Next element pointer T*next(T*) //gives Next element pointer

79 Generic Iterator Operation Operator * // Dereferance to access the Element Operator * // Dereferance to access the Element Operator ++ // For Moving To Next Element of Container we Need Increment Operator ++ // For Moving To Next Element of Container we Need Increment

80 Generic ITerator Example Template Template Class Iterator Class Iterator { CT* container; // Pointing container CT* container; // Pointing container ET* index; // For Accessing Element ET* index; // For Accessing Element …………………… ……………………

81 Generic ITerator Example Public; Public; Iterator (CT*c,bool pointAtfirst=true); Iterator (CT*c,bool pointAtfirst=true); Iterator(iterator &it);// Copy Constructor Iterator(iterator &it);// Copy Constructor Iterator&operator++();// increment; Iterator&operator++();// increment; ET&operator*(); ET&operator*(); Bool operator!=(iterator &it); Bool operator!=(iterator &it); }; };

82 Conclusion Iterator Allow the to change the Startegy without changing the Aggregate object Iterator Allow the to change the Startegy without changing the Aggregate object Iterator is Nothing but a Glorified pointer that has Encoded into class or pointer iterator is pointer to a container Iterator is Nothing but a Glorified pointer that has Encoded into class or pointer iterator is pointer to a container Iterator was best design for generic algorithm Iterator was best design for generic algorithm Iterator was similar to an ordinary object Iterator was similar to an ordinary object Iteratoer Stands to an container and pointer for array. Iteratoer Stands to an container and pointer for array.

83 PAPERS Describe three properties necessary a container to implement generic algorithms. Answer:- (Page 301) We claimed that this algorithm is generic, because it works for any aggregate object (container) that defines following three operations a. Increment operator (++) b. Dereferencing operator (*) c. Inequality operator (!=)

84 STL C++ programmer commonly use many Data Structure and Algorithms C++ programmer commonly use many Data Structure and Algorithms So C++ Standard Committee Added STL to C++ Standard Libraray So C++ Standard Committee Added STL to C++ Standard Libraray STL Data Structure and ALgoritm are Designed to operate Effienctly STL Data Structure and ALgoritm are Designed to operate Effienctly

85 STL HIERCHY STL ContainersIteratorsAlgorithms

86 Three Types of Container Container SequenceAssociative Container Adapter

87 Three Types of Sequence Container Sequence Container VectorDequeList

88 Four Types of Associative Associative Container SetMultiSetMapMultimap

89 Three Types of Container Adapter Container Adapter Stack LIFO Queue FIFo Priorty Queue

90 Iterator In STL Five Types ITERATOR Input Iterator OutPUT ITERATOR Forward Iterator Bidirectional Iterator Random Access Iterator

91 STL Advantages Advantages Reuse Saves development time and Cost Reuse Saves development time and Cost Onces Tested Component can be used Several Times Onces Tested Component can be used Several Times

92 STL Three Key Components Container(any data Structure ) Container(any data Structure ) Iterator Iterator Algorithm Algorithm

93 STL CONTAINER Container is an object that Contain Collection of Data Element Container is an object that Contain Collection of Data Element

94 STL THREE CONTAINERS STL Provides Three Containers STL Provides Three Containers Sequence Sequence Associative Associative Container Adapter Container Adapter

95 Sequence Container A sequence Organize a finite Set of Object,all of the Same Type, into a Strictly Linear Arrangement (ordinary Array) A sequence Organize a finite Set of Object,all of the Same Type, into a Strictly Linear Arrangement (ordinary Array) For Example A iron Chain For Example A iron Chain

96 Three Types of Sequence Container Vector: Vector: Rapid Inseration and Deletion at Back End Rapid Inseration and Deletion at Back End Random Access to Element Random Access to Element Deque: double Ended Queue Deque: double Ended Queue Rapid Inseration and Deletion at Front or Back Rapid Inseration and Deletion at Front or Back Random Access to Element Random Access to Element LIST  Doubly Link List: LIST  Doubly Link List: Rapid Inseration and Deletion at any Where Rapid Inseration and Deletion at any Where

97 VECTOR EXAMPLE #include #include Intmain() Intmain() { Std::vector iv;// Declaration Std::vector iv;// Declaration ………..push_back ………..push_back No pre Define Size It Automatically Grow No pre Define Size It Automatically Grow

98 Deque Example #include #include Intmain() Intmain() { Std::deque dq; Std::deque dq; dq.push_front(3); dq.push_front(3); // back(5); // back(5); …….. ……..

99 LIST Example #include #include Intmain() Intmain() { Std::list iv; Std::list iv; Push_back;;;;; Push_back;;;;;

100 Associative Container An Associative Container provides Fast Retrieval of Data based on Keys An Associative Container provides Fast Retrieval of Data based on Keys Associate a Key with A value Associate a Key with A value Key is easily Searchable Key is easily Searchable Key and Element Are Distinct two types Key and Element Are Distinct two types

101 Four Types of Associative Container Set : No Duplication For E.g Set of Integer Set : No Duplication For E.g Set of Integer Multi Set: Duplication Allow Multi Set: Duplication Allow Map: No Duplicate Key Map: No Duplicate Key Multimap: Duplicate Key Allows Multimap: Duplicate Key Allows D/F B/w Set and Map? D/F B/w Set and Map? In Set Element and Key are Same things In Set Element and Key are Same things In Map Element And Key are two Different Things In Map Element And Key are two Different Things

102 STL SET EXAMPLE #include #include Int main() Int main() { Std::Set cs; Std::Set cs; Cout<<”Size before inseration”<

103 Multi SET Example #include #include Int main() Int main() { Std::multiSet cs; Std::multiSet cs; Cout<<”Size before inseration”<

104 Map Example #include #include Int main() Int main() Typedef Std::map Typedef Std::map MyMap; MyMap; MyMap m; MyMap m; m.insert(My Map::value_type(1,a); m.insert(My Map::value_type(1,a); Key Element Type

105 First Class Container Sequence and Associative Container are Collectively reffered to as the First Class Container Sequence and Associative Container are Collectively reffered to as the First Class Container Underline DataStructure is First Class On Which Other are Build on it Underline DataStructure is First Class On Which Other are Build on it

106 Container Adapter A container Adapter is a Constrained version of Some Forst_class container A container Adapter is a Constrained version of Some Forst_class container

107 Three Type of Container Adapter Stack >>>>LIFO can Adapt Vector,Deque Stack >>>>LIFO can Adapt Vector,Deque Queue>>>FIFO can Adapt Deque or list Queue>>>FIFO can Adapt Deque or list Priority Queue>>>Return Element of Highest Priority Queue>>>Return Element of Highest Priorty,can Adapt vector of Deque Priorty,can Adapt vector of Deque

108 Common Function For All Container Default Constructor Default Constructor Copy Constructor Copy Constructor Destructor Destructor Empty()// Return If No Element Empty()// Return If No Element Max_size() // Return Maximum Num of Element Max_size() // Return Maximum Num of Element Size()//return Current number of Element Size()//return Current number of Element

109 Common Function For All Container Operator=() Operator=() // <=() // >() >=() >=() ==() ==() !=() !=() Swap() swap the Element of two Container

110 Common Function For All Container Begin() : return an iterator object that refers to the first element of the container Begin() : return an iterator object that refers to the first element of the container End() : return an iterator object that refers to the next position beyound the last element of the container End() : return an iterator object that refers to the next position beyound the last element of the container R begin(); return an iterator object that refers to the last element of the container R begin(); return an iterator object that refers to the last element of the container R end(); return an iterator object that refers to the position before the first element R end(); return an iterator object that refers to the position before the first element

111 Common Function For All Container Erase(iterator); removes an element pointed to by the iterator Erase(iterator); removes an element pointed to by the iterator Erase(iterator,iterator): removes the range of element specified by the first and the second iterator parameters Erase(iterator,iterator): removes the range of element specified by the first and the second iterator parameters Clear(); erases all element from the container Clear(); erases all element from the container

112 Container Requirements Each Container require Element type to provide a minimum set of functionality Each Container require Element type to provide a minimum set of functionality E.g E.g When an element is inserted into a container a copy of the element is made When an element is inserted into a container a copy of the element is made Copy Constructor Copy Constructor Assignemnt Operator Assignemnt Operator

113 Container Requirements Associative Container and Many Algorithm compare Element Associative Container and Many Algorithm compare Element Operator == Operator == Operator < Operator <

114 STL ITERATOR Iterator are type difines by STL Iterator are type difines by STL Iterator are for container Like Pointer are for ordinary Data Structure Iterator are for container Like Pointer are for ordinary Data Structure STL iterator provides pointer operation such as STL iterator provides pointer operation such as * and ++ * and ++

115 STL ITERATOR CATEGORIES There are Five Catgories There are Five Catgories Input iterator Input iterator Output Iterator Output Iterator Forward iterator Forward iterator Bi directional Iterator Bi directional Iterator Random Access Iterators Random Access Iterators

116 Input Iterators Can only read an element can only move on forward direction one element at a time Can only read an element can only move on forward direction one element at a time Support only one pass Al;gorithm Support only one pass Al;gorithm

117 Output Iterators Can only write an element can only move in forward direction one element at a time Can only write an element can only move in forward direction one element at a time Support only one pass Algorithm Support only one pass Algorithm

118 Forward Iterators Combine the capabilities of both input and output iterator in Addition they can book mark a position in the container Combine the capabilities of both input and output iterator in Addition they can book mark a position in the container

119 Bi direction Iterators Provide all the capabilities of forward iterator Provide all the capabilities of forward iterator In addition they can move in backward direction In addition they can move in backward direction As a result they support multi pass algorithm As a result they support multi pass algorithm

120 Random Access iterators Provide all Capabilities of bidirectional iterator Provide all Capabilities of bidirectional iterator In Addition they can Directly access any element of Container In Addition they can Directly access any element of Container

121 CONTAINER & ITERATOR TYPES Sequence Container : Sequence Container : Vector >>>>RA Vector >>>>RA Deque >>>RA Deque >>>RA List>>RA List>>RA ASSOCIATIVE CONTAINER ASSOCIATIVE CONTAINER Set>>>>>>bi directional Set>>>>>>bi directional Multiset>>>>BD Multiset>>>>BD Map>>>>>>BD Map>>>>>>BD Multimap>>>>BD Multimap>>>>BD

122 CONTAINER & ITERATOR TYPES Adapted Container Adapted Container Stack (none) Stack (none) Queue (none) Queue (none) Priority(none) Priority(none)

123 ALL ITERATOR OPERATION ++p ++p P++; P++; Input ITERAtor: Input ITERAtor: *P *P P1=P2 P1=P2 P1!=P2 P1!=P2 P==P2 P==P2

124 ALL ITERATOR OPERATION Output Iterator: Output Iterator: *P *P P1=P2 P1=P2 Forward Iterator: Forward Iterator: Combine op of both input and Output Combine op of both input and Output Bidirection : Bidirection : --p --p P-- P--

125 ALL ITERATOR OPERATION Random Access: Random Access: Beside the Operation of Bidirectional iterator Beside the Operation of Bidirectional iterator They can support They can support P+I // result is an iterator pointer P+I // result is an iterator pointer P-I // result is an iterator P-I // result is an iterator P+=I p1<=p2 P+=I p1<=p2 P-=I p1>=p2 P-=I p1>=p2 P[i] P[i] P1

126 Algorithm STL Include more than 70 Standard Algorithms these algorithm may use Iterator STL Include more than 70 Standard Algorithms these algorithm may use Iterator To manipulate container To manipulate container STL algoritm also Work for ordinary pointer and Data Type An Algorithm Work with a Particular container only if that Container Support a particular Iterator categories STL algoritm also Work for ordinary pointer and Data Type An Algorithm Work with a Particular container only if that Container Support a particular Iterator categories

127 Algorithm For E,g: a multipass Algorithm reqiuire bi directional iterator For E,g: a multipass Algorithm reqiuire bi directional iterator Examples Examples MULTATING SEQUENCES MULTATING SEQUENCES Copy,copy backward,Fill,Fill_n,remove,replace,sort,swap Copy,copy backward,Fill,Fill_n,remove,replace,sort,swap Non MULTATATING SEQUENCES: Non MULTATATING SEQUENCES: Adjacent_find,count,count_if,equal,max_elem ent,min_element,Search Adjacent_find,count,count_if,equal,max_elem ent,min_element,Search

128 Exception Handling Techniques For Error Handling Techniques For Error Handling Abnormal Termination Abnormal Termination GraceFull Termination GraceFull Termination Return the Illegal Termination Return the Illegal Termination Return Error Code From A function Return Error Code From A function Eception Handling Eception Handling

129 Abnormal Termination No ERROR Detection Compiler itself Close the Program.or We say Abnormal termination of Program No ERROR Detection Compiler itself Close the Program.or We say Abnormal termination of Program

130 GRACE FULL TERMINATION Program Can be design in a such away that instead of abnormal termination that can cause of wastage of resources,program perform clean up task,mean we add check for expected error Program Can be design in a such away that instead of abnormal termination that can cause of wastage of resources,program perform clean up task,mean we add check for expected error You Detect the Error and Inform to user that You Detect the Error and Inform to user that I cant Do and Application is Terminated by programmer I cant Do and Application is Terminated by programmer

131 Exception Handling

132 Summary!!!!! Most of the Topic are Skipped But Due to Lack of Time But Almost The important part is Cover!!! The Very Famous Quotation Most of the Topic are Skipped But Due to Lack of Time But Almost The important part is Cover!!! The Very Famous Quotation Practice make The Perfect Practice make The Perfect Contact US Contact US For Development of Software in For Development of Software in ASP. Net/Oracle/ C# other Web Designing ASP. Net/Oracle/ C# other Web Designing IT Solution Consultancy Company ….. IT Solution Consultancy Company …..

133 THAT ALL!!!! THANKS!!!!!!! THANKS!!!!!!! Your feed Back is Required & Prays Your feed Back is Required & Prays Wish You Best of Luck!!!!! Wish You Best of Luck!!!!! Admin!! Admin!! SHERY.KHAN………….. SHERY.KHAN………… // IT CONSULTANCY // IT CONSULTANCY


Download ppt "TEMPLATES Lecture 32-45 Presented By SHERY KHAN Object Orienting Programming."

Similar presentations


Ads by Google