SlideShare a Scribd company logo
TEMPLATES
IN
C++
K.THAMIZHSELVI
Asst. Prof. of Computer Science
Bon Secours college for Women,
Thanjavur
TEMPLATES
• Template is a new concept allow the function or class
to work on more than one data type at once without
writing different codes for different data types.
• The parameters used during its definition is of generic
type and can be replaced later by actual parameter.
• This is called the concept of generic programming
• The templates are also called as parameterized classes
or functions.
Purpose of Templates
• Used in large programs
• Code reusability
• Time saving
• Flexibility of program
• Used to create a family of classes or functions.
Types of Templates
• 2 types:
– Class Template
– Function Template
Class Templates
• A Class Template can represent various similar
classes operating on different data types.
Syntax:
template < class T1, class T2,…>
class classname
{
functions;
};
Eg:
template <class T>
class vector
{
T* v;
int size;
public:
vector (int m)
{
v = new T [size = m];
for ( int i = 0; i <size; i++)
v[i] = 0;
}
vector ( T* a)
{
for ( int i = 0; i <size; i++)
v[i] = a[i];
}
T operator* (vector &y)
{
T sum = 0;
for ( int i = 0; i <size; i++)
sum + = this -> v[i] * y . V [i];
return sum;
}
};
Template class
• A class created from a class template is called
a Template class.
classname < type> objectname (arglist);
• The process of creating a specific class from
class template is called Instantiation.
Class Templates with Multiple Parameters
• More than one generic data types can be used
in a class template.
• They can be declared by comma separated list
within the template specification.
template < class T1, class T2, …..>
class classname
{
………
body of the class
………
};
Example:
template <class T1, class T2>
Class Test
{
T1 a;
T2 b;
public :
Test (T1 x, T2 y)
{
a = x;
b = y;
}
void show()
{
cout<< a << “ and “ << b << “n”;
}
};
int main()
{
cout<< “Instantiating the class template test1:”;
Test < float, int > test1 (1.23, 123);
test1.show();
cout<< “Instantiating the class template test2:”;
Test < int, char > test2 (100, ‘w’);
test2.show();
return 0;
}
Output for the Program
Instantiating the class template test1: 1.23 and 123
Instantiating the class template test2: 100 and w
Function Templates
• Function templates used to create a family of
functions with different argument types.
Syntax:
Template < class T>
returntype functionname (arguments of type T)
{
body of the function
}
Example
template < class T>
void swap ( T &x, T &y)
{
T temp = x;
x = y;
y = temp;
}
Function Template With Multiple Parameters
Syntax:
template < class T1, class T2,….>
returntype functionname(arguments of types T1,T2,..)
{
body of the function
}
Example:
template < class T1, class T2>
void display ( T1 x, T2 y)
{
cout << x “ “ << y << “n”;
}
int main()
{
cout << “calling function template with integer and character
string type parameters…n”;
display( 2000, “ECG”);
cout << “calling function template with float and integer type
parameters…n”;
display( 2.12, 212);
return 0;
}
Output
calling function template with integer and
character string type parameters…
2000 ECG
calling function template with integer and
character string type parameters…
2.12 212
Templates in c++

More Related Content

What's hot

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
Amit Trivedi
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
Mayank Bhatt
 
Templates
TemplatesTemplates
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Dr Sukhpal Singh Gill
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructorHaresh Jaiswal
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
Pranali Chaudhari
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 

What's hot (20)

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Constructor
ConstructorConstructor
Constructor
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Templates
TemplatesTemplates
Templates
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
structure and union
structure and unionstructure and union
structure and union
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 

Similar to Templates in c++

Templates c++ - prashant odhavani - 160920107003
Templates   c++ - prashant odhavani - 160920107003Templates   c++ - prashant odhavani - 160920107003
Templates c++ - prashant odhavani - 160920107003
Prashant odhavani
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
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
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
Saiganesh124618
 
Templates2
Templates2Templates2
Templates2
zindadili
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Templates1
Templates1Templates1
Templates1
zindadili
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
Class template
Class templateClass template
Class template
Kousalya M
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
Muhammad khan
 
C++ Templates. SFINAE
C++ Templates. SFINAEC++ Templates. SFINAE
C++ Templates. SFINAE
GlobalLogic Ukraine
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
C#2
C#2C#2
Data structures and algorithms lab2
Data structures and algorithms lab2Data structures and algorithms lab2
Data structures and algorithms lab2Bianca Teşilă
 
template c++.pptx
template c++.pptxtemplate c++.pptx
template c++.pptx
SANJUSANJEEVTOPPO
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
Nicola Bonelli
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
BhushanLilhare
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
kinan keshkeh
 

Similar to Templates in c++ (20)

Templates c++ - prashant odhavani - 160920107003
Templates   c++ - prashant odhavani - 160920107003Templates   c++ - prashant odhavani - 160920107003
Templates c++ - prashant odhavani - 160920107003
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
 
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
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
Templates2
Templates2Templates2
Templates2
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates1
Templates1Templates1
Templates1
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Class template
Class templateClass template
Class template
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
C++ Templates. SFINAE
C++ Templates. SFINAEC++ Templates. SFINAE
C++ Templates. SFINAE
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
C#2
C#2C#2
C#2
 
Data structures and algorithms lab2
Data structures and algorithms lab2Data structures and algorithms lab2
Data structures and algorithms lab2
 
template c++.pptx
template c++.pptxtemplate c++.pptx
template c++.pptx
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 

More from ThamizhselviKrishnam

Standard template library
Standard template libraryStandard template library
Standard template library
ThamizhselviKrishnam
 
Operators and expression in c++
Operators and  expression in c++Operators and  expression in c++
Operators and expression in c++
ThamizhselviKrishnam
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++
ThamizhselviKrishnam
 
Page maker - working with text
Page maker - working with textPage maker - working with text
Page maker - working with text
ThamizhselviKrishnam
 
Microprocessor & architecture
Microprocessor & architectureMicroprocessor & architecture
Microprocessor & architecture
ThamizhselviKrishnam
 
Instruction set of 8085
Instruction set of 8085Instruction set of 8085
Instruction set of 8085
ThamizhselviKrishnam
 
Memory and storage devices
Memory and storage devicesMemory and storage devices
Memory and storage devices
ThamizhselviKrishnam
 
Generations of computer
Generations of computerGenerations of computer
Generations of computer
ThamizhselviKrishnam
 
Adobe Pagemaker 7.0
Adobe Pagemaker 7.0Adobe Pagemaker 7.0
Adobe Pagemaker 7.0
ThamizhselviKrishnam
 
classification of digital computer
classification of digital computerclassification of digital computer
classification of digital computer
ThamizhselviKrishnam
 
Pagemaker
PagemakerPagemaker

More from ThamizhselviKrishnam (11)

Standard template library
Standard template libraryStandard template library
Standard template library
 
Operators and expression in c++
Operators and  expression in c++Operators and  expression in c++
Operators and expression in c++
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++
 
Page maker - working with text
Page maker - working with textPage maker - working with text
Page maker - working with text
 
Microprocessor & architecture
Microprocessor & architectureMicroprocessor & architecture
Microprocessor & architecture
 
Instruction set of 8085
Instruction set of 8085Instruction set of 8085
Instruction set of 8085
 
Memory and storage devices
Memory and storage devicesMemory and storage devices
Memory and storage devices
 
Generations of computer
Generations of computerGenerations of computer
Generations of computer
 
Adobe Pagemaker 7.0
Adobe Pagemaker 7.0Adobe Pagemaker 7.0
Adobe Pagemaker 7.0
 
classification of digital computer
classification of digital computerclassification of digital computer
classification of digital computer
 
Pagemaker
PagemakerPagemaker
Pagemaker
 

Recently uploaded

SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdfSCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SELF-EXPLANATORY
 
extra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdfextra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdf
DiyaBiswas10
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
muralinath2
 
erythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptxerythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptx
muralinath2
 
Comparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebratesComparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebrates
sachin783648
 
Viksit bharat till 2047 India@2047.pptx
Viksit bharat till 2047  India@2047.pptxViksit bharat till 2047  India@2047.pptx
Viksit bharat till 2047 India@2047.pptx
rakeshsharma20142015
 
Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...
Sérgio Sacani
 
EY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptxEY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptx
AlguinaldoKong
 
Mammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also FunctionsMammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also Functions
YOGESH DOGRA
 
Large scale production of streptomycin.pptx
Large scale production of streptomycin.pptxLarge scale production of streptomycin.pptx
Large scale production of streptomycin.pptx
Cherry
 
filosofia boliviana introducción jsjdjd.pptx
filosofia boliviana introducción jsjdjd.pptxfilosofia boliviana introducción jsjdjd.pptx
filosofia boliviana introducción jsjdjd.pptx
IvanMallco1
 
Predicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdfPredicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdf
binhminhvu04
 
Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
Richard Gill
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
Lokesh Patil
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
Scintica Instrumentation
 
Citrus Greening Disease and its Management
Citrus Greening Disease and its ManagementCitrus Greening Disease and its Management
Citrus Greening Disease and its Management
subedisuryaofficial
 
ESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptxESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptx
muralinath2
 
Hemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptxHemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptx
muralinath2
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
kumarmathi863
 
NuGOweek 2024 Ghent - programme - final version
NuGOweek 2024 Ghent - programme - final versionNuGOweek 2024 Ghent - programme - final version
NuGOweek 2024 Ghent - programme - final version
pablovgd
 

Recently uploaded (20)

SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdfSCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
 
extra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdfextra-chromosomal-inheritance[1].pptx.pdfpdf
extra-chromosomal-inheritance[1].pptx.pdfpdf
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
 
erythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptxerythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptx
 
Comparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebratesComparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebrates
 
Viksit bharat till 2047 India@2047.pptx
Viksit bharat till 2047  India@2047.pptxViksit bharat till 2047  India@2047.pptx
Viksit bharat till 2047 India@2047.pptx
 
Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...
 
EY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptxEY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptx
 
Mammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also FunctionsMammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also Functions
 
Large scale production of streptomycin.pptx
Large scale production of streptomycin.pptxLarge scale production of streptomycin.pptx
Large scale production of streptomycin.pptx
 
filosofia boliviana introducción jsjdjd.pptx
filosofia boliviana introducción jsjdjd.pptxfilosofia boliviana introducción jsjdjd.pptx
filosofia boliviana introducción jsjdjd.pptx
 
Predicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdfPredicting property prices with machine learning algorithms.pdf
Predicting property prices with machine learning algorithms.pdf
 
Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
 
Citrus Greening Disease and its Management
Citrus Greening Disease and its ManagementCitrus Greening Disease and its Management
Citrus Greening Disease and its Management
 
ESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptxESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptx
 
Hemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptxHemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptx
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
 
NuGOweek 2024 Ghent - programme - final version
NuGOweek 2024 Ghent - programme - final versionNuGOweek 2024 Ghent - programme - final version
NuGOweek 2024 Ghent - programme - final version
 

Templates in c++

  • 1. TEMPLATES IN C++ K.THAMIZHSELVI Asst. Prof. of Computer Science Bon Secours college for Women, Thanjavur
  • 2. TEMPLATES • Template is a new concept allow the function or class to work on more than one data type at once without writing different codes for different data types. • The parameters used during its definition is of generic type and can be replaced later by actual parameter. • This is called the concept of generic programming • The templates are also called as parameterized classes or functions.
  • 3. Purpose of Templates • Used in large programs • Code reusability • Time saving • Flexibility of program • Used to create a family of classes or functions.
  • 4. Types of Templates • 2 types: – Class Template – Function Template
  • 5. Class Templates • A Class Template can represent various similar classes operating on different data types. Syntax: template < class T1, class T2,…> class classname { functions; };
  • 6. Eg: template <class T> class vector { T* v; int size; public: vector (int m) { v = new T [size = m]; for ( int i = 0; i <size; i++) v[i] = 0; } vector ( T* a) { for ( int i = 0; i <size; i++) v[i] = a[i]; } T operator* (vector &y) { T sum = 0; for ( int i = 0; i <size; i++) sum + = this -> v[i] * y . V [i]; return sum; } };
  • 7. Template class • A class created from a class template is called a Template class. classname < type> objectname (arglist); • The process of creating a specific class from class template is called Instantiation.
  • 8. Class Templates with Multiple Parameters • More than one generic data types can be used in a class template. • They can be declared by comma separated list within the template specification. template < class T1, class T2, …..> class classname { ……… body of the class ……… };
  • 9. Example: template <class T1, class T2> Class Test { T1 a; T2 b; public : Test (T1 x, T2 y) { a = x; b = y; } void show() { cout<< a << “ and “ << b << “n”; } };
  • 10. int main() { cout<< “Instantiating the class template test1:”; Test < float, int > test1 (1.23, 123); test1.show(); cout<< “Instantiating the class template test2:”; Test < int, char > test2 (100, ‘w’); test2.show(); return 0; }
  • 11. Output for the Program Instantiating the class template test1: 1.23 and 123 Instantiating the class template test2: 100 and w
  • 12. Function Templates • Function templates used to create a family of functions with different argument types. Syntax: Template < class T> returntype functionname (arguments of type T) { body of the function }
  • 13. Example template < class T> void swap ( T &x, T &y) { T temp = x; x = y; y = temp; }
  • 14. Function Template With Multiple Parameters Syntax: template < class T1, class T2,….> returntype functionname(arguments of types T1,T2,..) { body of the function }
  • 15. Example: template < class T1, class T2> void display ( T1 x, T2 y) { cout << x “ “ << y << “n”; } int main() { cout << “calling function template with integer and character string type parameters…n”; display( 2000, “ECG”); cout << “calling function template with float and integer type parameters…n”; display( 2.12, 212); return 0; }
  • 16. Output calling function template with integer and character string type parameters… 2000 ECG calling function template with integer and character string type parameters… 2.12 212