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)

Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
functions of C++
functions of C++functions of C++
functions of C++
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Operator Overloading & Function Overloading
Operator Overloading & Function OverloadingOperator Overloading & Function Overloading
Operator Overloading & Function Overloading
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Characteristics of OOPS
Characteristics of OOPS Characteristics of OOPS
Characteristics of OOPS
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
encapsulation
encapsulationencapsulation
encapsulation
 

Destacado (20)

Templates
TemplatesTemplates
Templates
 
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++
 
Exception handling
Exception handlingException handling
Exception handling
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
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
 
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
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 

Último

Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Último (20)

Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

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 };