SlideShare a Scribd company logo
TEMPLATES
Pranali P. Chaudhari
INTRODUCTION
 Template enable us to define generic
classes and functions and thus provides
support for generic programming.
 Generic programming is an approach
where generic types are used as
parameters in algorithms so that they
work for a variety of data types.
INTRODUCTION
 A template can be used to create a family of
classes or functions.
 For eg: a class template for an array class
would enable us to create arrays of various data
types such as: int, float etc.
 Templates are also known as parameterized
classes or functions.
 Template is a simple process to create a generic
class with an anonymous type.
Class Templates
 The class template definition is very similar to
an ordinary class definition except the prefix
template <class T> and the use of type T.
 A class created from class template is called a
template class.
 Syntax:
 classname<type> objectname(arglist)
 The process of creating a specific class from a
class template is called instantiation.
Class Templates
 General format of class template is:
template <class T>
class classname
{
//…………..
//class member specification with
//anonymous type T wherever appropriate
//…….
};
Class Templates (Example)
class vector
{
int *v;
int size;
public:
vector (int m)
{
v= new int [ size = m];
for(int i=0; i<size; i++)
v[i]=0;
}
vector (int * a)
{
for(int i=0; i<size; i++)
v[i]=a[i];
}
int operator * (vector &y)
{
int sum=0;
for (int i=0; i<size; i++)
sum += this -> v[i] * y . v[i];
return sum;
}
}
int main()
{
int x[3] = {1,2,3};
int y[3]= {4,5,6};
vector v1(3);
vector v2(3);
v1 = x ;
v2 = y ;
int R = v1 * v2 ;
cout<< “ R = “ << R ;
return 0;
}
Class Templates (Example)
const size = 3;
template<class T>
class vector
{
T * v;
public:
vector()
{
v=new T[size];
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;
}
}
Class Templates (Example)
int main()
{
int x[3] = {1,2,3};
int y[3] = {4,5,6};
vector <int> V1;
vector <int> V2;
V1 = x;
V2 = y;
int R = V1 * V2;
cout << “R = “ << R;
return 0;
}
Class Templates with Multiple Parameters
 We can use more than one generic data
type in a class template.
 Syntax:
template <class T1, class T2>
class classname
{
………
………
………
};
Class Templates with Multiple Parameters
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;
cout<<b;
}
};
int main()
{
Test <float, int> test1(1.23,123);
Test <int, char> test2(100,’W’);
test1.show();
test2.show();
return 0;
}
Output:
1.23
123
100
W
Function Templates
 Function templates are used to create a
family of functions with different
argument types.
 Syntax:
template <class T>
returntype functionname (arguments of type T)
{
………..
………..
}
Function Template
Template <class T>
void swap (T &x, T &y)
{
T temp = x;
x = y;
y = temp;
}
void fun(int m, int n,
float a, float b)
{
swap(m, n);
swap(a, b);
}
int main()
{
fun(100, 200, 11.22, 33.44);
return 0;
}
Function Template with Multiple
Parameters
 We can have more than one generic
data type in the function template.
template < class T1, class T2>
returntype functionname(arguments of type T1, T2…)
{
…….. (Body of function)
………
}
Function Template with Multiple
Parameters
template <class T1, class T2>
void display(T1 x, T2 y)
{
cout<<x <<“ “ << y << “n”;
}
int main()
{
display(1999, “XYZ”);
display (12.34, 1234);
return 0;
}
Overloading of Template Functions
 A template function may be overloaded either
by template functions or ordinary functions of
its name.
 The overloading is accomplished as follows:
 Call an ordinary function that has an exact match.
 Call a template function that could be created with an
exact match.
 Try normal overloading to ordinary function and call
the one that matches.
Overloading of Template Functions
template < class T>
void display(T x)
{
cout<<“Template Display : “ << x << “n”;
}
void display(int x)
{
cout << “Explicit Display: “ << x << “n”;
}
int main()
{
display(100);
display(12.34);
display(‘C’);
return 0;
}
Member Function Template
 Member functions of the template classes themselves
are parameterized by the type argument.
 Thus, member functions must be defined by the
function templates.
 Syntax:
Template <class T>
returntype classname <T> :: functionname(arglist)
{
…….. // function body
……..
}
Member Function Template
(Example)
template<class T>
class vector
{
T *v;
int size;
public:
vector(int m);
vector(T * a);
T operator *(vector & y);
};
Member Function Template
(Example)
//member function templates….
template <class T>
vector<T> :: vector(int m)
{
v = new T[size = m];
for(int i=0; i<size; i++)
v[i] = 0;
}
template <class T>
vector<T> :: vector(T * a)
{
for(int i=0; i<size; i++)
v[i] = a[i];
}
template <class T>
T vector<T> :: operator * (vector &y)
{
T sum = 0;
for (int i=0; i<size; i++)
sum += this -> v[i] * y.v[i];
return sum;
}
Non-Type Template Arguments
 It is also possible to use non-type arguments.
 In addition to the type argument T, we can
also use other arguments such as strings, int,
float, built-in types.
 Example:
template <class T, int size>
class array
{
T a[size];
……..
………
};
Non-Type Template Arguments
 This template supplies the size of the array as an
argument.
 The argument must be specified whenever a
template class is created.
 Example:
 array <int, 10> a1; // Array of 10 integers
 array <float, 5> a2; // Array of 5 floats
 array <char, 20> a3; // String of size 20
Summary
 C++ supports template to implement the
concept of ______.
 _____ allows to generate a family of classes
or functions to handle different data types.
 A specific class created from a class template
is called ________.
 The process of creating a template class is
known as ________.
 Like other functions, template functions can
be overloaded. (True/False)
 Non-type parameters can also be used as an
arguments templates. (True/False)
Short Answer Questions
 What is generic programming? How it is
implemented in C++?
 Generic programming is an approach where
generic types are used as parameters in
algorithms so that they work for a variety of
data types.
 Generic programming is implemented using the
templates in C++.
 A template can be considered as a kind of
macro. Then, what is the difference between
them.
 Macros are not type safe, that is a macro
defined for integer operations cannot accept
float data.
Short Answer Questions
 Distinguish between overloaded functions
and function templates.
 Function templates involve telling a function
that it will be receiving a specified data type
and then it will work with that at compile time.
 The difference with this and function
overloading is that function overloading can
define multiple behaviours of function with the
same name and multiple/various inputs.
Short Answer Questions
 Distinguish between class template
and template class.
 Class template is generic class for
different types of objects. Basically it
provides a specification for
generating classes based on
parameters.
 Template classes are those classes that
are defined using a class template.
Short Answer Questions
 A class template is known as a
parameterized class. Comment.
 As template is defined with a
parameter that would be replaced by a
specified data type at the time of actual
use of class it is also known as
parameterized class.
Short Answer Questions
 Write a function template for finding the
minimum value contained in an array.
template <class T>
T findMin(T arr[],int n)
{
int i;
T min;
min=arr[0];
for(i=0;i<n;i++)
{
if(min > arr[i])
min=arr[i];
}
return(min);
}
Example Program
References
 Object Oriented Programming with
C++ by E. Balagurusamy.
END OF UNIT ….

More Related Content

What's hot

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
Sathish Narayanan
 
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
Harendra Singh
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
Vishesh Jha
 
Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
MOHIT TOMAR
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 

What's hot (20)

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
String functions in C
String functions in CString functions in C
String functions in C
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
virtual function
virtual functionvirtual function
virtual function
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 

Similar to Templates

Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
Muhammad khan
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Templates2
Templates2Templates2
Templates2
zindadili
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
Mayank Bhatt
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
Nicola Bonelli
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
saranuru
 
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
 
Templates1
Templates1Templates1
Templates1
zindadili
 
TEMPLATES in C++
TEMPLATES in C++TEMPLATES in C++
TEMPLATES in C++
Prof Ansari
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
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
 
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
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
Docent Education
 
Class template
Class templateClass template
Class template
Kousalya M
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
guestf0562b
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 
C++ Templates. SFINAE
C++ Templates. SFINAEC++ Templates. SFINAE
C++ Templates. SFINAE
GlobalLogic Ukraine
 

Similar to Templates (20)

Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates2
Templates2Templates2
Templates2
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
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
 
Templates1
Templates1Templates1
Templates1
 
TEMPLATES in C++
TEMPLATES in C++TEMPLATES in C++
TEMPLATES in C++
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
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
 
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
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Class template
Class templateClass template
Class template
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
C++ Templates. SFINAE
C++ Templates. SFINAEC++ Templates. SFINAE
C++ Templates. SFINAE
 

More from Pranali Chaudhari

Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
Pranali Chaudhari
 
Inheritance
InheritanceInheritance
Inheritance
Pranali Chaudhari
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
Pranali Chaudhari
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Pranali Chaudhari
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Pranali Chaudhari
 

More from Pranali Chaudhari (8)

Exception handling
Exception handlingException handling
Exception handling
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 

Recently uploaded

Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
Kamal Acharya
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 

Recently uploaded (20)

Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 

Templates

  • 2. INTRODUCTION  Template enable us to define generic classes and functions and thus provides support for generic programming.  Generic programming is an approach where generic types are used as parameters in algorithms so that they work for a variety of data types.
  • 3. INTRODUCTION  A template can be used to create a family of classes or functions.  For eg: a class template for an array class would enable us to create arrays of various data types such as: int, float etc.  Templates are also known as parameterized classes or functions.  Template is a simple process to create a generic class with an anonymous type.
  • 4. Class Templates  The class template definition is very similar to an ordinary class definition except the prefix template <class T> and the use of type T.  A class created from class template is called a template class.  Syntax:  classname<type> objectname(arglist)  The process of creating a specific class from a class template is called instantiation.
  • 5. Class Templates  General format of class template is: template <class T> class classname { //………….. //class member specification with //anonymous type T wherever appropriate //……. };
  • 6. Class Templates (Example) class vector { int *v; int size; public: vector (int m) { v= new int [ size = m]; for(int i=0; i<size; i++) v[i]=0; } vector (int * a) { for(int i=0; i<size; i++) v[i]=a[i]; } int operator * (vector &y) { int sum=0; for (int i=0; i<size; i++) sum += this -> v[i] * y . v[i]; return sum; } } int main() { int x[3] = {1,2,3}; int y[3]= {4,5,6}; vector v1(3); vector v2(3); v1 = x ; v2 = y ; int R = v1 * v2 ; cout<< “ R = “ << R ; return 0; }
  • 7. Class Templates (Example) const size = 3; template<class T> class vector { T * v; public: vector() { v=new T[size]; 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; } }
  • 8. Class Templates (Example) int main() { int x[3] = {1,2,3}; int y[3] = {4,5,6}; vector <int> V1; vector <int> V2; V1 = x; V2 = y; int R = V1 * V2; cout << “R = “ << R; return 0; }
  • 9. Class Templates with Multiple Parameters  We can use more than one generic data type in a class template.  Syntax: template <class T1, class T2> class classname { ……… ……… ……… };
  • 10. Class Templates with Multiple Parameters 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; cout<<b; } }; int main() { Test <float, int> test1(1.23,123); Test <int, char> test2(100,’W’); test1.show(); test2.show(); return 0; } Output: 1.23 123 100 W
  • 11. Function Templates  Function templates are used to create a family of functions with different argument types.  Syntax: template <class T> returntype functionname (arguments of type T) { ……….. ……….. }
  • 12. Function Template Template <class T> void swap (T &x, T &y) { T temp = x; x = y; y = temp; } void fun(int m, int n, float a, float b) { swap(m, n); swap(a, b); } int main() { fun(100, 200, 11.22, 33.44); return 0; }
  • 13. Function Template with Multiple Parameters  We can have more than one generic data type in the function template. template < class T1, class T2> returntype functionname(arguments of type T1, T2…) { …….. (Body of function) ……… }
  • 14. Function Template with Multiple Parameters template <class T1, class T2> void display(T1 x, T2 y) { cout<<x <<“ “ << y << “n”; } int main() { display(1999, “XYZ”); display (12.34, 1234); return 0; }
  • 15. Overloading of Template Functions  A template function may be overloaded either by template functions or ordinary functions of its name.  The overloading is accomplished as follows:  Call an ordinary function that has an exact match.  Call a template function that could be created with an exact match.  Try normal overloading to ordinary function and call the one that matches.
  • 16. Overloading of Template Functions template < class T> void display(T x) { cout<<“Template Display : “ << x << “n”; } void display(int x) { cout << “Explicit Display: “ << x << “n”; } int main() { display(100); display(12.34); display(‘C’); return 0; }
  • 17. Member Function Template  Member functions of the template classes themselves are parameterized by the type argument.  Thus, member functions must be defined by the function templates.  Syntax: Template <class T> returntype classname <T> :: functionname(arglist) { …….. // function body …….. }
  • 18. Member Function Template (Example) template<class T> class vector { T *v; int size; public: vector(int m); vector(T * a); T operator *(vector & y); };
  • 19. Member Function Template (Example) //member function templates…. template <class T> vector<T> :: vector(int m) { v = new T[size = m]; for(int i=0; i<size; i++) v[i] = 0; } template <class T> vector<T> :: vector(T * a) { for(int i=0; i<size; i++) v[i] = a[i]; } template <class T> T vector<T> :: operator * (vector &y) { T sum = 0; for (int i=0; i<size; i++) sum += this -> v[i] * y.v[i]; return sum; }
  • 20. Non-Type Template Arguments  It is also possible to use non-type arguments.  In addition to the type argument T, we can also use other arguments such as strings, int, float, built-in types.  Example: template <class T, int size> class array { T a[size]; …….. ……… };
  • 21. Non-Type Template Arguments  This template supplies the size of the array as an argument.  The argument must be specified whenever a template class is created.  Example:  array <int, 10> a1; // Array of 10 integers  array <float, 5> a2; // Array of 5 floats  array <char, 20> a3; // String of size 20
  • 22. Summary  C++ supports template to implement the concept of ______.  _____ allows to generate a family of classes or functions to handle different data types.  A specific class created from a class template is called ________.  The process of creating a template class is known as ________.  Like other functions, template functions can be overloaded. (True/False)  Non-type parameters can also be used as an arguments templates. (True/False)
  • 23. Short Answer Questions  What is generic programming? How it is implemented in C++?  Generic programming is an approach where generic types are used as parameters in algorithms so that they work for a variety of data types.  Generic programming is implemented using the templates in C++.  A template can be considered as a kind of macro. Then, what is the difference between them.  Macros are not type safe, that is a macro defined for integer operations cannot accept float data.
  • 24. Short Answer Questions  Distinguish between overloaded functions and function templates.  Function templates involve telling a function that it will be receiving a specified data type and then it will work with that at compile time.  The difference with this and function overloading is that function overloading can define multiple behaviours of function with the same name and multiple/various inputs.
  • 25. Short Answer Questions  Distinguish between class template and template class.  Class template is generic class for different types of objects. Basically it provides a specification for generating classes based on parameters.  Template classes are those classes that are defined using a class template.
  • 26. Short Answer Questions  A class template is known as a parameterized class. Comment.  As template is defined with a parameter that would be replaced by a specified data type at the time of actual use of class it is also known as parameterized class.
  • 27. Short Answer Questions  Write a function template for finding the minimum value contained in an array. template <class T> T findMin(T arr[],int n) { int i; T min; min=arr[0]; for(i=0;i<n;i++) { if(min > arr[i]) min=arr[i]; } return(min); } Example Program
  • 28. References  Object Oriented Programming with C++ by E. Balagurusamy.
  • 29. END OF UNIT ….