SlideShare a Scribd company logo
1 of 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
};

More Related Content

What's hot

Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentationManeesha Caldera
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overridingRajab Ali
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branchingSaranya saran
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loopsbsdeol28
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in cyazad dumasia
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 

What's hot (20)

Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
Function Parameters
Function ParametersFunction Parameters
Function Parameters
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Strings
StringsStrings
Strings
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 

Viewers also liked (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
 
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
 

Similar to 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
 

Recently uploaded

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 

Recently uploaded (20)

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 

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