SlideShare a Scribd company logo
1 of 16
Download to read offline
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 FunctionTemplate
• 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
};

More Related Content

What's hot (20)

Array within a class
Array within a classArray within a class
Array within a class
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
Arrays
ArraysArrays
Arrays
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
 
C# Cheat Sheet
C# Cheat SheetC# Cheat Sheet
C# Cheat Sheet
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Loops in R
Loops in RLoops in R
Loops in R
 
Arrays
ArraysArrays
Arrays
 
Stack queue
Stack queueStack queue
Stack queue
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programming
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 

Similar to Templates2 (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
 
C++ [Submission] - submit the driver program (DvcSchedule1.cpp) and .pdf
C++ [Submission] - submit the driver program (DvcSchedule1.cpp) and .pdfC++ [Submission] - submit the driver program (DvcSchedule1.cpp) and .pdf
C++ [Submission] - submit the driver program (DvcSchedule1.cpp) and .pdf
 
B T0065
B T0065B T0065
B T0065
 
Bt0065
Bt0065Bt0065
Bt0065
 
Templates
TemplatesTemplates
Templates
 
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
 
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
 
OOP
OOPOOP
OOP
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 

More from zindadili

Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaingzindadili
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Polymorphism
PolymorphismPolymorphism
Polymorphismzindadili
 
Function overloading
Function overloadingFunction overloading
Function overloadingzindadili
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritancezindadili
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritancezindadili
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritancezindadili
 
Abstraction1
Abstraction1Abstraction1
Abstraction1zindadili
 
Access specifier
Access specifierAccess specifier
Access specifierzindadili
 
Friend function
Friend functionFriend function
Friend functionzindadili
 

More from zindadili (20)

Namespaces
NamespacesNamespaces
Namespaces
 
Namespace1
Namespace1Namespace1
Namespace1
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Templates1
Templates1Templates1
Templates1
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Aggregation
AggregationAggregation
Aggregation
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritance
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritance
 
Abstraction1
Abstraction1Abstraction1
Abstraction1
 
Abstraction
AbstractionAbstraction
Abstraction
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Inheritance
InheritanceInheritance
Inheritance
 
Friend function
Friend functionFriend function
Friend function
 
Enum
EnumEnum
Enum
 

Recently uploaded

Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationMJDuyan
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRATanmoy Mishra
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxAditiChauhan701637
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICESayali Powar
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17Celine George
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxraviapr7
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17Celine George
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and stepobaje godwin sunday
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsEugene Lysak
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxEduSkills OECD
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 

Recently uploaded (20)

Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive Education
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptx
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICE
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptx
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and step
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George Wells
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 

Templates2

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