SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
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 ….

Weitere ähnliche Inhalte

Was ist angesagt?

Union in c language
Union  in c languageUnion  in c language
Union in c languagetanmaymodi4
 
Function template
Function templateFunction template
Function templateKousalya M
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayimtiazalijoono
 
Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and UnionsAshim Lamichhane
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++imran khan
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Strings in c
Strings in cStrings in c
Strings in cvampugani
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 

Was ist angesagt? (20)

Union in c language
Union  in c languageUnion  in c language
Union in c language
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Function template
Function templateFunction template
Function template
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Array in c#
Array in c#Array in c#
Array in c#
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Strings in c
Strings in cStrings in c
Strings in c
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 

Ähnlich wie 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
 
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#
 
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
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 

Mehr von Pranali Chaudhari

Mehr von 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
 

Kürzlich hochgeladen

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfSuman Jyoti
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfrs7054576148
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 

Kürzlich hochgeladen (20)

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 

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 ….