SlideShare una empresa de Scribd logo
1 de 16
Object Oriented Programming
using C++
Topic : Templates in C++
Templates
• Templates support generic programming, which allows to
develop reusable software components such as function,
class, etc.
• Supporting different data types in a single framework.
• A template in C++ allows the construction of a family of
template functions and classes to perform the same
operation on different data types.
• The templates declared for functions are called function
templates and those declared for classes are called class
templates.
• It allows a single template to deal with a generic data
type T.
Function Templates
• There are several functions of considerable importance
which have to be used frequently with different data
types.
• The limitation of such functions is that they operate only
on a particular data type.
• It can be overcome by defining that function as a function
template or generic function.
• Syntax:
template <class T, …..>
returntype function_name (arguments)
{
…… // body of template function
……
}
Ex : Multipe swap functions
#include<iostream.h>
Void swap(char &x, char &y)
{ char t;
t = x; x = y; y = t;
}
Void swap(int &x, int &y)
{ int t;
t = x; x = y; y = t;
}
Void swap(float &x, float &y)
{ float t;
t = x; x = y; y = t;
}
Void main()
{
char ch1, ch2;
cout<<“n Enter values : ”;
cin>>ch1>>ch2;
swap(ch1,ch2);
cout<<“n After swap ch1 =
”<<ch1<<“ ch2 = ”<<ch2;
int a, b;
cout<<“n Enter values : ”;
cin>>a>>b;
swap(a,b);
cout<<“n After swap a =
”<<a<<“ b = ”<<b;
float c, d;
cout<<“n Enter values : ”;
cin>>c>>d;
swap(c,d);
cout<<“n After swap c =
”<<c<<“ d = ”<<d;
}
Output:
Enter values : R K
After swap ch1 = K
ch2 = R
Enter values : 5 10
After swap a = 10
b = 5
Enter values : 20.5 99.3
After swap c = 99.3
d = 20.5
Generic fuction for swapping
#include<iostream.h>
Template<class T>
Void swap(T &x, T &y)
{ T t;
t = x; x = y; y = t;
}
Void main()
{
char ch1, ch2;
cout<<“n Enter values : ”;
cin>>ch1>>ch2;
swap(ch1,ch2);
cout<<“n After swap ch1 =
”<<ch1<<“ ch2 = ”<<ch2;
int a, b;
cout<<“n Enter values : ”;
cin>>a>>b;
swap(a,b);
cout<<“n After swap a =
”<<a<<“ b = ”<<b;
float c, d;
cout<<“n Enter values : ”;
cin>>c>>d;
swap(c,d);
cout<<“n After swap c =
”<<c<<“ d = ”<<d;
}
output :
same as previous example
Function and Function Template
• Function templates are not suitable for handling all data
types, and hence, it is necessary to override function
templates by using normal functions for specific data types.
Ex: #include<iostream.h>
#include<string.h>
template <class T>
T max(T a, T b)
{ if(a>b)
return a;
else
return b;
}
char *max(char *a, char *b)
{ if(strcmp(a,b)>0)
return a;
else
return b;
}
void main()
{
char ch,ch1,ch2;
cout<<“n Enter two
char value : ”;
cin>>ch1>>ch2;
ch=max(ch1,ch2);
cout<<“n max value ”
<<ch;
int a,b,c;
cout<<“n Enter two int
values : ”;
cin>>a>>b;
c=max(a,b);
cout<<“n max value : ”<<c;
char str1[20],str2[20];
cout<<“n Enter two str
values : ”;
cin>>str1>>str2;
cout<<“n max value : ”
<<max(str1,str2);
}
Output :
Enter two char value : A Z
Max value : Z
Enter two int value : 12 20
Max value : 20
Enter two char value :
Tejaswi Rajkumar
Max value : Tejaswi
• In the above example if we not use the normal function,
when a statement call such as,
max(str1,str2)
• It is executed, but it will not produce the desired result.
The above call compares memory addresses of strings
instead of their contents.
• The logic for comparing strings is different from
comparing integer and floating point data types.
• It requires the normal function having the definition but
not the function template.
• We can use both the normal function and function
template in a same program.
Overloaded Function
Templates
• The function template can also be overloaded with
multiple declarations.
• It may be overloaded either by functions of its mane or
by template functions of the same name.
• Similar to overloading of normal functions, overloaded
functions must differ either in terms of number of
parameters or their types.
Ex : #include<iostream.h>
template <class T>
void print(T data)
{ cout<<data<<endl; }
template <class T>
void print(T data, int
ntimes)
{ for(int i=0;i<ntimes;i++)
cout<<data<<endl;
}
void main()
{ print(1);
print(1.5);
print(520,2);
print(“OOP is Great”,3)
}
Output :
1
1.5
520
520
OOP is Great
OOP is Great
OOP is Great
Class Templates
• Class can also be declared to operate on different data
types. Such class are called class templates.
• A class template specifies how individual classes can be
constructed similar to normal class specification.
• These classes model a generic class which support
similar operations for different data types.
• Syntax :
template <class T1, class T2, …..>
class class_name
{
T1 data1; // data items of template type
void func1 (T1 a, T2 &b); // function of template
argument
T func2 (T2 *x, T2 *y);
}
Example :
Class charstack
{ char array[25];
unsigned int top;
public:
charstack();
void push(const char
&element);
char pop(void);
unsigned int getsize
(void) const;
};
Class intstack
{ int array[25];
unsigned int top;
public:
intstack();
void push(const int
&element);
int pop(void);
unsigned int getsize
(void) const;
};
Class doublestack
{ double array[25];
unsigned int top;
public:
doublestack();
void push(const
double &element);
double pop(void);
unsigned int getsize
(void) const;
};
• In the previous example, a separate stack class is
required for each and every data types. Templates
declaration enables subatitution of code for all the three
declarations of stacks with a single template class as
follows :
template<class T>
class datastack
{ T array[25];
unsigned int top;
public:
doublestack();
void push(const double &element);
double pop(void);
unsigned int getsize (void) const;
};
Inheritance of Class Template
Use of templates with respect to inheritance involves the
followings :
• Derive a class template from a base class, which is a
template class.
• Derive a class template from a base class, which is a
template class, add more template members in the
derived class.
• Derive a class from a base class which is not a template,
and template member to that class.
• Derive a class from a base class which is a template
class and restrict the template feature, so that the
derived class and its derivatives do not have the
template feature.
The syntax for declaring derived classes from template-
based base classes is as :
template <class T1, …..>
class baseclass
{
// template type data and functions
};
template <class T1, …..>
class derivedclass : public baseclass <T1, ….>
{
// template type data and functions
};

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm Analysis
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
File in C language
File in C languageFile in C language
File in C language
 
Java IO
Java IOJava IO
Java IO
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Learn C
Learn CLearn C
Learn C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
File in c
File in cFile in c
File in c
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 

Destacado

Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
Template at c++
Template at c++Template at c++
Template at c++Lusain Kim
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template LibraryIlio Catallo
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Laxman Puri
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Anil Bapat
 
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...Rishikesh Agrawani
 

Destacado (20)

Templates
TemplatesTemplates
Templates
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
file handling c++
file handling c++file handling c++
file handling c++
 
polymorphism
polymorphism polymorphism
polymorphism
 
C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
 
Template at c++
Template at c++Template at c++
Template at c++
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
functions of C++
functions of C++functions of C++
functions of C++
 
Exception handling
Exception handlingException handling
Exception handling
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++
 
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
 

Similar a Templates presentation (20)

TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templates
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Bt0065
Bt0065Bt0065
Bt0065
 
B T0065
B T0065B T0065
B T0065
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Templates
TemplatesTemplates
Templates
 
Session 4
Session 4Session 4
Session 4
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
OOP
OOPOOP
OOP
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Templates
TemplatesTemplates
Templates
 
Bc0037
Bc0037Bc0037
Bc0037
 

Último

Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 

Último (20)

Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 

Templates presentation

  • 1. Object Oriented Programming using C++ Topic : Templates in C++
  • 2. Templates • Templates support generic programming, which allows to develop reusable software components such as function, class, etc. • Supporting different data types in a single framework. • A template in C++ allows the construction of a family of template functions and classes to perform the same operation on different data types. • The templates declared for functions are called function templates and those declared for classes are called class templates. • It allows a single template to deal with a generic data type T.
  • 3. Function Templates • There are several functions of considerable importance which have to be used frequently with different data types. • The limitation of such functions is that they operate only on a particular data type. • It can be overcome by defining that function as a function template or generic function. • Syntax: template <class T, …..> returntype function_name (arguments) { …… // body of template function …… }
  • 4. Ex : Multipe swap functions #include<iostream.h> Void swap(char &x, char &y) { char t; t = x; x = y; y = t; } Void swap(int &x, int &y) { int t; t = x; x = y; y = t; } Void swap(float &x, float &y) { float t; t = x; x = y; y = t; } Void main() { char ch1, ch2; cout<<“n Enter values : ”; cin>>ch1>>ch2; swap(ch1,ch2); cout<<“n After swap ch1 = ”<<ch1<<“ ch2 = ”<<ch2; int a, b; cout<<“n Enter values : ”; cin>>a>>b; swap(a,b); cout<<“n After swap a = ”<<a<<“ b = ”<<b;
  • 5. float c, d; cout<<“n Enter values : ”; cin>>c>>d; swap(c,d); cout<<“n After swap c = ”<<c<<“ d = ”<<d; } Output: Enter values : R K After swap ch1 = K ch2 = R Enter values : 5 10 After swap a = 10 b = 5 Enter values : 20.5 99.3 After swap c = 99.3 d = 20.5
  • 6. Generic fuction for swapping #include<iostream.h> Template<class T> Void swap(T &x, T &y) { T t; t = x; x = y; y = t; } Void main() { char ch1, ch2; cout<<“n Enter values : ”; cin>>ch1>>ch2; swap(ch1,ch2); cout<<“n After swap ch1 = ”<<ch1<<“ ch2 = ”<<ch2; int a, b; cout<<“n Enter values : ”; cin>>a>>b; swap(a,b); cout<<“n After swap a = ”<<a<<“ b = ”<<b; float c, d; cout<<“n Enter values : ”; cin>>c>>d; swap(c,d); cout<<“n After swap c = ”<<c<<“ d = ”<<d; } output : same as previous example
  • 7. Function and Function Template • Function templates are not suitable for handling all data types, and hence, it is necessary to override function templates by using normal functions for specific data types. Ex: #include<iostream.h> #include<string.h> template <class T> T max(T a, T b) { if(a>b) return a; else return b; } char *max(char *a, char *b) { if(strcmp(a,b)>0) return a; else return b; } void main() { char ch,ch1,ch2; cout<<“n Enter two char value : ”; cin>>ch1>>ch2; ch=max(ch1,ch2); cout<<“n max value ” <<ch;
  • 8. int a,b,c; cout<<“n Enter two int values : ”; cin>>a>>b; c=max(a,b); cout<<“n max value : ”<<c; char str1[20],str2[20]; cout<<“n Enter two str values : ”; cin>>str1>>str2; cout<<“n max value : ” <<max(str1,str2); } Output : Enter two char value : A Z Max value : Z Enter two int value : 12 20 Max value : 20 Enter two char value : Tejaswi Rajkumar Max value : Tejaswi
  • 9. • In the above example if we not use the normal function, when a statement call such as, max(str1,str2) • It is executed, but it will not produce the desired result. The above call compares memory addresses of strings instead of their contents. • The logic for comparing strings is different from comparing integer and floating point data types. • It requires the normal function having the definition but not the function template. • We can use both the normal function and function template in a same program.
  • 10. Overloaded Function Templates • The function template can also be overloaded with multiple declarations. • It may be overloaded either by functions of its mane or by template functions of the same name. • Similar to overloading of normal functions, overloaded functions must differ either in terms of number of parameters or their types.
  • 11. Ex : #include<iostream.h> template <class T> void print(T data) { cout<<data<<endl; } template <class T> void print(T data, int ntimes) { for(int i=0;i<ntimes;i++) cout<<data<<endl; } void main() { print(1); print(1.5); print(520,2); print(“OOP is Great”,3) } Output : 1 1.5 520 520 OOP is Great OOP is Great OOP is Great
  • 12. Class Templates • Class can also be declared to operate on different data types. Such class are called class templates. • A class template specifies how individual classes can be constructed similar to normal class specification. • These classes model a generic class which support similar operations for different data types. • Syntax : template <class T1, class T2, …..> class class_name { T1 data1; // data items of template type void func1 (T1 a, T2 &b); // function of template argument T func2 (T2 *x, T2 *y); }
  • 13. Example : Class charstack { char array[25]; unsigned int top; public: charstack(); void push(const char &element); char pop(void); unsigned int getsize (void) const; }; Class intstack { int array[25]; unsigned int top; public: intstack(); void push(const int &element); int pop(void); unsigned int getsize (void) const; }; Class doublestack { double array[25]; unsigned int top; public: doublestack(); void push(const double &element); double pop(void); unsigned int getsize (void) const; };
  • 14. • In the previous example, a separate stack class is required for each and every data types. Templates declaration enables subatitution of code for all the three declarations of stacks with a single template class as follows : template<class T> class datastack { T array[25]; unsigned int top; public: doublestack(); void push(const double &element); double pop(void); unsigned int getsize (void) const; };
  • 15. Inheritance of Class Template Use of templates with respect to inheritance involves the followings : • Derive a class template from a base class, which is a template class. • Derive a class template from a base class, which is a template class, add more template members in the derived class. • Derive a class from a base class which is not a template, and template member to that class. • Derive a class from a base class which is a template class and restrict the template feature, so that the derived class and its derivatives do not have the template feature.
  • 16. The syntax for declaring derived classes from template- based base classes is as : template <class T1, …..> class baseclass { // template type data and functions }; template <class T1, …..> class derivedclass : public baseclass <T1, ….> { // template type data and functions };