SlideShare a Scribd company logo
1 of 55
Definition:
 Templates are used to define generic definition of
functions or classes.
 A template is not related to specific data types and
can work with different data types.
 Can re-use same code with int, string, etc.
There are two types of templates:
Function templates
Class templates
 Function templates are special functions that can
operate with generic types.
 This allows us to create a function template whose
functionality can be adapted to more than one
type or class without repeating the entire code for
each type.
 Same code is re-used for different types
Syntax:
template <class T>
T FunctionName (Parameter (s));
Example:
#include<iostream.h>
#include<conio.h>
using namespace std;
template<class T>
void swap(T&x,T &y)
{
t temp=x;
x=y;
y=temp;
}
void fun(int a,int b,float c,float d)
{
cout<<"na and b before swaping
:"<<a<<"t"<<b;
swap(a,b);
cout<<"na and b after
swaping :"<<a<<"t"<<b;
cout<<"nnc and d before swaping
:"<<c<<"t"<<d;
swap(c,d);
cout<<"nc and d after
swaping :"<<c<<"t"<<d;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter A,B values(integer):";
cin>>a>>b;
cout<<"Enter C,D values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}
Output:
Enter A, B values (integer): 10 20
Enter C, D values (float): 2.50 10.80
A and B before swapping: 10 20
A and B after swapping: 20 10
C and D before swapping: 2.50 10.80
C and D after swapping: 10.80 2.50
Program:
#include<iostream>
#include<conio.h>
using namespace std;
template <class Type>
Type Max(Type a, Type b)
{
if(a>b)
return a;
else
return b;
}
Void main()
{
int n;
float m;
n=Max(10, 50);
cout<<“Maximum of two integers:“<<n<<endl;
m=Max(4.8, 2.2);
Cout<<“Maximum of two float: “<<m<<endl;
getch();
}
Output:
Maximum of two integers: 50
Maximum of two floats:4.8
Class templates are generally
used for data storage classes.
Stacks and linked lists are
examples of data storage
classes.
The examples of these
classes(data storage classes)
that we present could store data
of only a single basic type.
The example shown, could
store data only of type “int”
that is:
 class Stack
 {
› private:
 int st[MAX]; //array of int
 int top; //index number of top of
stack
› public:
 Stack(); //constructor
 void push(int var); //takes int as argument
 int pop(); //returns int value
 };
If we wanted to store data of
type long in a stack, we would
need to define a completely
new class.
 class LongStack
 {
› private:
 long st[MAX]; //array of longs
 long top; //index number of top of stack
› public:
 LongStack(); //constructor
 void push(long var); //takes long as argument
 long pop(); //returns long value
 };
Templates make it
possible to use one
function or class to
handle different data
types.
 The basic syntax for declaring
template class:
 template <class Type>
 class Cont
 {
› ……
 };
Example of class template
that handle variables of all /
different data types is shown
 // tempstak.cpp
 // implements stack class as a template
 #include <iostream.h>
 using namespace std;
 const int MAX = 100; //size of array
 template <class Type>
 class Stack
 {
 private:
 Type st[MAX]; //stack: array of any type
 int top; //number of top of stack
 public:
 Stack() //constructor
 { top = -1; }
 void push(Type var) //put number on stack
 { st[++top] = var; }
 Type pop() //take number off stack
 { return st[top--]; }
 int main()
 {
 Stack<float> s1; //s1 is object of class Stack<float>
 s1.push(1111.1F); //push 3 floats, pop 3 floats
 s1.push(2222.2F);
 s1.push(3333.3F);
 cout << “1: “ << s1.pop() << endl;
 cout << “2: “ << s1.pop() << endl;
 cout << “3: “ << s1.pop() << endl;
 Stack<long> s2; //s2 is object of class Stack<long>
 s2.push(123123123L); //push 3 longs, pop 3 longs
 s2.push(234234234L);
 s2.push(345345345L);
 cout << “1: “ << s2.pop() << endl;
 cout << “2: “ << s2.pop() << endl;
 cout << “3: “ << s2.pop() << endl;
 return 0;
 }
1: 3333.3 //float stack
2: 2222.2
3: 1111.1
1: 345345345 //long stack
2: 234234234
3: 123123123
 Class templates differ from function
templates in the way they are
instantiated.
 To create an actual function from a
function template, you call it using
arguments of a specific type.
 Old C language signaled many errors for
returning a particular value from the
functions.
 Setjump() and Longjump() functions
were used for handling errors there (very
difficult to use).
 This approach is not appropriate in C++.
 It handles errors in a different way using
“Exceptions”.
The exception syntax consists of:
 First of all, there should be an exception
class.
 Throw Exception (To handle an error)
 Try Block (A code that uses objects)
 Catch Block (Catches exception
through member function)
 // not a working program
 class AClass //a class
 {
 public:
 class AnError //exception class
 {
 };
 void Func() //a member function
 {
 if( /* error condition */ )
 throw AnError(); //throw exception
 }
 };
 int main() //application
 {
 try //try block
 {
 AClass obj1; //interact with AClass objects
 obj1.Func(); //may cause error
 }
 catch(AClass::AnError) //exception handler
 { //(catch block)
 //tell user about error, etc.
 }
 return 0;
 }
// demonstrates exceptions
 #include <iostream>
 using namespace std;
 const int MAX = 3; //stack holds 3 integers
 class Stack
 {
 private:
 int st[MAX]; //array of integers
 int top; //index of top of stack
 public:
 class Range //exception class for Stack
 { //note: empty class body
 };
 Stack() //constructor
 { top = -1; }
 void push(int var)
 {
 if(top >= MAX-1) //if stack full,
 throw Range(); //throw exception
 st[++top] = var; //put number on stack
 }
 int pop()
 {
 if(top < 0) //if stack empty,
 throw Range(); //throw exception
 return st[top--]; //take number off stack
 }
 };
 int main()
 {
 Stack s1;
 try
 {
 s1.push(11);
 s1.push(22);
 s1.push(33);
 // s1.push(44); //oops: stack full
 cout << “1: “ << s1.pop() << endl;
 cout << “2: “ << s1.pop() << endl;
 cout << “3: “ << s1.pop() << endl;
 cout << “4: “ << s1.pop() << endl; //oops: stack empty
 catch(Stack::Range) //exception handler
 {
 cout << “Exception: Stack Full or Empty” << endl;
 }
 cout << “Arrive here after catch (or normal exit)” << endl;
 return 0;
 }
 First of all, exception class should be
specified as follows:
Class Range
{ empty class body};
 Exception will occur in previous program
if application tries to pop a value when
stack is empty and push a value when
stack is full.
 Throw Range() will perform this task here.
 Statements that manipulate stack (class
name) objects, are enclosed in try block.
try
{
//code that operates on objects that
might cause exception
}
 Code that handles exceptions is
enclosed in braces, preceded by catch
keyword.
catch(stack::Range)
{
//code that handles exception
}
 Normal execution outside try block.
 Control enters the try block.
 An error occurs in try block (in main
function).
 Member function throws an exception.
 Control transfers to exception handler.
// demonstrates two exception handlers
 #include <iostream>
 using namespace std;
 const int MAX = 3; //stack holds 3 integers
 class Stack
 {
 private:
 int st[MAX]; //stack: array of integers
 int top; //index of top of stack
 public:
 class Full { }; //exception class
 class Empty { }; //exception class
 Stack() //constructor
 { top = -1; }
 void push(int var) //put number on stack
 {
 if(top >= MAX-1) //if stack full,
 throw Full(); //throw Full exception
 st[++top] = var;
 }
 int pop() //take number off stack
 {
 if(top < 0) //if stack empty,
 throw Empty(); //throw Empty exception
 return st[top--];
 }
 };
 int main()
 {
 Stack s1;
 try
 {
 s1.push(11);
 s1.push(22);
 s1.push(33);
 // s1.push(44); //oops: stack full
 cout << “1: “ << s1.pop() << endl;
 cout << “2: “ << s1.pop() << endl;
 cout << “3: “ << s1.pop() << endl;
 cout << “4: “ << s1.pop() << endl; //oops: stack empty
 }
 catch(Stack::Full)
 {
 cout << “Exception: Stack Full” << endl;
 }
 catch(Stack::Empty)
 {
 cout << “Exception: Stack Empty” << endl;
 }
 return 0;
 }
 // exceptions with arguments
 #include <iostream>
 #include <string>
 using namespace std;
 class Distance //English Distance class
 {
 private:
 int feet;
 float inches;
 public
 class InchesEx //exception class
 {
 public:
 string origin; //for name of routine
 float iValue; //for faulty inches value
 InchesEx(string or, float in) //2-arg constructor
 {
 origin = or; //store string
 iValue = in; //store inches
 }
 }; //end of exception class
 Distance() //constructor (no args)
 { feet = 0; inches = 0.0; }
 Distance(int ft, float in) //constructor (two args)
 {
 if(in >= 12.0)
 throw InchesEx(“2-arg constructor”, in);
 feet = ft;
 inches = in;
 }
 void getdist() //get length from user
 {
 cout << “nEnter feet: “; cin >> feet;
 cout << “Enter inches: “; cin >> inches;
 if(inches >= 12.0)
 throw InchesEx(“getdist() function”, inches);
 }
 void showdist() //display distance
 { cout << feet << “‟-” << inches << „”‟; }
 };
 int main()
 {
 Distance dist1(17, 3.5); //2-arg constructor
 Distance dist2; //no-arg constructor
 dist2.getdist(); //get value
 //display distances
 cout << “ndist1 = “; dist1.showdist();
 cout << “ndist2 = “; dist2.showdist();
 }
 catch(Distance::InchesEx ix) //exception handler
 {
 cout << “nInitialization error in “ << ix.origin
 << “.n Inches value of “ << ix.iValue
 << “ is too large.”;
 }
 cout << endl;
 return 0;
 }
 The exception statements need not be in
the try block directly.
 It can be in a function that is called by a
statement in try block.
 However, try part must be included
before catch part.
 The class libraries sold by any developer
may contain errors. They can cause
problems. These problems can be
resolved using Exceptions.
 Do not use exceptions for simple
purposes that can be solved using loops
and other structures. Use exceptions for
handling difficult tasks only because they
effect the program size.
 In exception mechanism, destructors are
called automatically. So the space
reserved by them is swiped clean easily.
 Code in every exception will be reset.
 When you catch an
exception, sometimes you terminate
your application. Exception mechanism
cleans up chores before terminating. In
short, it executes destructors. If there is no
exception handler, the program is
terminated by operating system.
Templates
Templates

More Related Content

What's hot

C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
Rishikesh Agrawani
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 

What's hot (20)

Array within a class
Array within a classArray within a class
Array within a class
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
C program
C programC program
C program
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Arrays
ArraysArrays
Arrays
 
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
C++ Templates_ Program to Swap Two Numbers Using Function Template - The Craz...
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Java programs
Java programsJava programs
Java programs
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
Loops in R
Loops in RLoops in R
Loops in R
 
Array strings
Array stringsArray strings
Array strings
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Arrays
ArraysArrays
Arrays
 
Java generics
Java genericsJava generics
Java generics
 
Type Casting Operator
Type Casting OperatorType Casting Operator
Type Casting Operator
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Data struture lab
Data struture labData struture lab
Data struture lab
 
C programs
C programsC programs
C programs
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 

Viewers also liked

Viewers also liked (20)

Cohen sutherland algorithm
Cohen sutherland algorithmCohen sutherland algorithm
Cohen sutherland algorithm
 
Summary of Simultaneous Multithreading: Maximizing On-Chip Parallelism
Summary of Simultaneous Multithreading: Maximizing On-Chip ParallelismSummary of Simultaneous Multithreading: Maximizing On-Chip Parallelism
Summary of Simultaneous Multithreading: Maximizing On-Chip Parallelism
 
JAVA Manual remaining
JAVA Manual remainingJAVA Manual remaining
JAVA Manual remaining
 
Manual of JAVA (more than Half)
Manual of JAVA (more than Half)Manual of JAVA (more than Half)
Manual of JAVA (more than Half)
 
Raster images (assignment)
Raster images (assignment)Raster images (assignment)
Raster images (assignment)
 
Linear combination of vector
Linear combination of vectorLinear combination of vector
Linear combination of vector
 
Scaling
ScalingScaling
Scaling
 
Applications of Image Processing
Applications of Image ProcessingApplications of Image Processing
Applications of Image Processing
 
Digital logic and design's Lab 4 nand
Digital logic and design's Lab 4 nandDigital logic and design's Lab 4 nand
Digital logic and design's Lab 4 nand
 
Digital logic and design's Lab 3
Digital logic and design's Lab 3Digital logic and design's Lab 3
Digital logic and design's Lab 3
 
Prefix and suffix of open gl
Prefix and suffix of open glPrefix and suffix of open gl
Prefix and suffix of open gl
 
Javadocx j option pane
Javadocx j option paneJavadocx j option pane
Javadocx j option pane
 
Tomasulo Algorithm
Tomasulo AlgorithmTomasulo Algorithm
Tomasulo Algorithm
 
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
 
Mission statement and Vision statement of 3 Different Companies
Mission statement and Vision statement of 3 Different CompaniesMission statement and Vision statement of 3 Different Companies
Mission statement and Vision statement of 3 Different Companies
 
IPv6 Implementation challenges
IPv6 Implementation challengesIPv6 Implementation challenges
IPv6 Implementation challenges
 
Implementation & Challenges of IPv6
Implementation & Challenges of IPv6Implementation & Challenges of IPv6
Implementation & Challenges of IPv6
 
DLDLab 8 half adder
DLDLab 8 half adderDLDLab 8 half adder
DLDLab 8 half adder
 
Graphic display devices
Graphic display devicesGraphic display devices
Graphic display devices
 
Memory Hierarchy Design, Basics, Cache Optimization, Address Translation
Memory Hierarchy Design, Basics, Cache Optimization, Address TranslationMemory Hierarchy Design, Basics, Cache Optimization, Address Translation
Memory Hierarchy Design, Basics, Cache Optimization, Address Translation
 

Similar to Templates

Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
fsenterprises
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
mohdjakirfb
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docx
adkinspaige22
 
computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8
ecomputernotes
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
afgt2012
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
shericehewat
 

Similar to Templates (20)

Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
 
Namespaces
NamespacesNamespaces
Namespaces
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docx
 
computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
STLStack.pdf
STLStack.pdfSTLStack.pdf
STLStack.pdf
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Stacks
StacksStacks
Stacks
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Chapter03
Chapter03Chapter03
Chapter03
 

More from Farwa Ansari

More from Farwa Ansari (10)

Energy Harvesting Techniques in Wireless Sensor Networks – A Survey
Energy Harvesting Techniques in Wireless Sensor Networks – A SurveyEnergy Harvesting Techniques in Wireless Sensor Networks – A Survey
Energy Harvesting Techniques in Wireless Sensor Networks – A Survey
 
Micro-services architecture
Micro-services architectureMicro-services architecture
Micro-services architecture
 
Software Design Patterns - An Overview
Software Design Patterns - An OverviewSoftware Design Patterns - An Overview
Software Design Patterns - An Overview
 
Optimizing the memory management of a virtual machine monitor on a NUMA syste...
Optimizing the memory management of a virtual machine monitor on a NUMA syste...Optimizing the memory management of a virtual machine monitor on a NUMA syste...
Optimizing the memory management of a virtual machine monitor on a NUMA syste...
 
Fault Tolerance Typed Assembly Language - A graphical overview
Fault Tolerance Typed Assembly Language - A graphical overviewFault Tolerance Typed Assembly Language - A graphical overview
Fault Tolerance Typed Assembly Language - A graphical overview
 
Comparative Analysis of Face Recognition Methodologies and Techniques
Comparative Analysis of Face Recognition Methodologies and TechniquesComparative Analysis of Face Recognition Methodologies and Techniques
Comparative Analysis of Face Recognition Methodologies and Techniques
 
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
 
Business plan of a software house
Business plan of a software houseBusiness plan of a software house
Business plan of a software house
 
Dld (lab 1 & 2)
Dld (lab 1 & 2)Dld (lab 1 & 2)
Dld (lab 1 & 2)
 
Hacking and Hackers
Hacking and HackersHacking and Hackers
Hacking and Hackers
 

Recently uploaded

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

Templates

  • 1.
  • 2.
  • 3.
  • 4. Definition:  Templates are used to define generic definition of functions or classes.  A template is not related to specific data types and can work with different data types.  Can re-use same code with int, string, etc.
  • 5. There are two types of templates: Function templates Class templates
  • 6.  Function templates are special functions that can operate with generic types.  This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.  Same code is re-used for different types
  • 7. Syntax: template <class T> T FunctionName (Parameter (s));
  • 8. Example: #include<iostream.h> #include<conio.h> using namespace std; template<class T> void swap(T&x,T &y) { t temp=x; x=y; y=temp; } void fun(int a,int b,float c,float d) { cout<<"na and b before swaping :"<<a<<"t"<<b; swap(a,b); cout<<"na and b after swaping :"<<a<<"t"<<b; cout<<"nnc and d before swaping :"<<c<<"t"<<d; swap(c,d); cout<<"nc and d after swaping :"<<c<<"t"<<d; } void main() { int a,b; float c,d; clrscr(); cout<<"Enter A,B values(integer):"; cin>>a>>b; cout<<"Enter C,D values(float):"; cin>>c>>d; fun(a,b,c,d); getch(); }
  • 9. Output: Enter A, B values (integer): 10 20 Enter C, D values (float): 2.50 10.80 A and B before swapping: 10 20 A and B after swapping: 20 10 C and D before swapping: 2.50 10.80 C and D after swapping: 10.80 2.50
  • 10. Program: #include<iostream> #include<conio.h> using namespace std; template <class Type> Type Max(Type a, Type b) { if(a>b) return a; else return b; } Void main() { int n; float m; n=Max(10, 50); cout<<“Maximum of two integers:“<<n<<endl; m=Max(4.8, 2.2); Cout<<“Maximum of two float: “<<m<<endl; getch(); } Output: Maximum of two integers: 50 Maximum of two floats:4.8
  • 11.
  • 12. Class templates are generally used for data storage classes. Stacks and linked lists are examples of data storage classes. The examples of these classes(data storage classes) that we present could store data of only a single basic type.
  • 13. The example shown, could store data only of type “int” that is:
  • 14.  class Stack  { › private:  int st[MAX]; //array of int  int top; //index number of top of stack › public:  Stack(); //constructor  void push(int var); //takes int as argument  int pop(); //returns int value  };
  • 15. If we wanted to store data of type long in a stack, we would need to define a completely new class.
  • 16.  class LongStack  { › private:  long st[MAX]; //array of longs  long top; //index number of top of stack › public:  LongStack(); //constructor  void push(long var); //takes long as argument  long pop(); //returns long value  };
  • 17. Templates make it possible to use one function or class to handle different data types.
  • 18.  The basic syntax for declaring template class:  template <class Type>  class Cont  { › ……  };
  • 19. Example of class template that handle variables of all / different data types is shown
  • 20.  // tempstak.cpp  // implements stack class as a template  #include <iostream.h>  using namespace std;  const int MAX = 100; //size of array  template <class Type>  class Stack  {  private:  Type st[MAX]; //stack: array of any type  int top; //number of top of stack  public:  Stack() //constructor  { top = -1; }  void push(Type var) //put number on stack  { st[++top] = var; }  Type pop() //take number off stack  { return st[top--]; }
  • 21.  int main()  {  Stack<float> s1; //s1 is object of class Stack<float>  s1.push(1111.1F); //push 3 floats, pop 3 floats  s1.push(2222.2F);  s1.push(3333.3F);  cout << “1: “ << s1.pop() << endl;  cout << “2: “ << s1.pop() << endl;  cout << “3: “ << s1.pop() << endl;  Stack<long> s2; //s2 is object of class Stack<long>  s2.push(123123123L); //push 3 longs, pop 3 longs  s2.push(234234234L);  s2.push(345345345L);  cout << “1: “ << s2.pop() << endl;  cout << “2: “ << s2.pop() << endl;  cout << “3: “ << s2.pop() << endl;  return 0;  }
  • 22. 1: 3333.3 //float stack 2: 2222.2 3: 1111.1 1: 345345345 //long stack 2: 234234234 3: 123123123
  • 23.
  • 24.  Class templates differ from function templates in the way they are instantiated.  To create an actual function from a function template, you call it using arguments of a specific type.
  • 25.
  • 26.  Old C language signaled many errors for returning a particular value from the functions.  Setjump() and Longjump() functions were used for handling errors there (very difficult to use).  This approach is not appropriate in C++.  It handles errors in a different way using “Exceptions”.
  • 27. The exception syntax consists of:  First of all, there should be an exception class.  Throw Exception (To handle an error)  Try Block (A code that uses objects)  Catch Block (Catches exception through member function)
  • 28.
  • 29.  // not a working program  class AClass //a class  {  public:  class AnError //exception class  {  };  void Func() //a member function  {  if( /* error condition */ )  throw AnError(); //throw exception  }  };  int main() //application  {  try //try block  {  AClass obj1; //interact with AClass objects  obj1.Func(); //may cause error  }  catch(AClass::AnError) //exception handler  { //(catch block)  //tell user about error, etc.  }  return 0;  }
  • 30. // demonstrates exceptions  #include <iostream>  using namespace std;  const int MAX = 3; //stack holds 3 integers  class Stack  {  private:  int st[MAX]; //array of integers  int top; //index of top of stack  public:  class Range //exception class for Stack  { //note: empty class body  };
  • 31.  Stack() //constructor  { top = -1; }  void push(int var)  {  if(top >= MAX-1) //if stack full,  throw Range(); //throw exception  st[++top] = var; //put number on stack  }  int pop()  {  if(top < 0) //if stack empty,  throw Range(); //throw exception  return st[top--]; //take number off stack  }  };
  • 32.  int main()  {  Stack s1;  try  {  s1.push(11);  s1.push(22);  s1.push(33);  // s1.push(44); //oops: stack full  cout << “1: “ << s1.pop() << endl;  cout << “2: “ << s1.pop() << endl;  cout << “3: “ << s1.pop() << endl;  cout << “4: “ << s1.pop() << endl; //oops: stack empty  catch(Stack::Range) //exception handler  {  cout << “Exception: Stack Full or Empty” << endl;  }  cout << “Arrive here after catch (or normal exit)” << endl;  return 0;  }
  • 33.
  • 34.  First of all, exception class should be specified as follows: Class Range { empty class body};
  • 35.  Exception will occur in previous program if application tries to pop a value when stack is empty and push a value when stack is full.  Throw Range() will perform this task here.
  • 36.  Statements that manipulate stack (class name) objects, are enclosed in try block. try { //code that operates on objects that might cause exception }
  • 37.  Code that handles exceptions is enclosed in braces, preceded by catch keyword. catch(stack::Range) { //code that handles exception }
  • 38.  Normal execution outside try block.  Control enters the try block.  An error occurs in try block (in main function).  Member function throws an exception.  Control transfers to exception handler.
  • 39. // demonstrates two exception handlers  #include <iostream>  using namespace std;  const int MAX = 3; //stack holds 3 integers  class Stack  {  private:  int st[MAX]; //stack: array of integers  int top; //index of top of stack  public:  class Full { }; //exception class  class Empty { }; //exception class  Stack() //constructor  { top = -1; }  void push(int var) //put number on stack  {  if(top >= MAX-1) //if stack full,  throw Full(); //throw Full exception  st[++top] = var;  }
  • 40.  int pop() //take number off stack  {  if(top < 0) //if stack empty,  throw Empty(); //throw Empty exception  return st[top--];  }  };  int main()  {  Stack s1;  try  {  s1.push(11);  s1.push(22);
  • 41.  s1.push(33);  // s1.push(44); //oops: stack full  cout << “1: “ << s1.pop() << endl;  cout << “2: “ << s1.pop() << endl;  cout << “3: “ << s1.pop() << endl;  cout << “4: “ << s1.pop() << endl; //oops: stack empty  }  catch(Stack::Full)  {  cout << “Exception: Stack Full” << endl;  }  catch(Stack::Empty)  {  cout << “Exception: Stack Empty” << endl;  }  return 0;  }
  • 42.
  • 43.  // exceptions with arguments  #include <iostream>  #include <string>  using namespace std;  class Distance //English Distance class  {  private:  int feet;  float inches;  public  class InchesEx //exception class  {
  • 44.  public:  string origin; //for name of routine  float iValue; //for faulty inches value  InchesEx(string or, float in) //2-arg constructor  {  origin = or; //store string  iValue = in; //store inches  }  }; //end of exception class  Distance() //constructor (no args)  { feet = 0; inches = 0.0; }
  • 45.  Distance(int ft, float in) //constructor (two args)  {  if(in >= 12.0)  throw InchesEx(“2-arg constructor”, in);  feet = ft;  inches = in;  }  void getdist() //get length from user  {  cout << “nEnter feet: “; cin >> feet;  cout << “Enter inches: “; cin >> inches;
  • 46.  if(inches >= 12.0)  throw InchesEx(“getdist() function”, inches);  }  void showdist() //display distance  { cout << feet << “‟-” << inches << „”‟; }  };  int main()  {  Distance dist1(17, 3.5); //2-arg constructor  Distance dist2; //no-arg constructor  dist2.getdist(); //get value  //display distances
  • 47.  cout << “ndist1 = “; dist1.showdist();  cout << “ndist2 = “; dist2.showdist();  }  catch(Distance::InchesEx ix) //exception handler  {  cout << “nInitialization error in “ << ix.origin  << “.n Inches value of “ << ix.iValue  << “ is too large.”;  }  cout << endl;  return 0;  }
  • 48.
  • 49.  The exception statements need not be in the try block directly.  It can be in a function that is called by a statement in try block.  However, try part must be included before catch part.
  • 50.  The class libraries sold by any developer may contain errors. They can cause problems. These problems can be resolved using Exceptions.
  • 51.  Do not use exceptions for simple purposes that can be solved using loops and other structures. Use exceptions for handling difficult tasks only because they effect the program size.
  • 52.  In exception mechanism, destructors are called automatically. So the space reserved by them is swiped clean easily.  Code in every exception will be reset.
  • 53.  When you catch an exception, sometimes you terminate your application. Exception mechanism cleans up chores before terminating. In short, it executes destructors. If there is no exception handler, the program is terminated by operating system.

Editor's Notes

  1. The keyword &apos;class&apos; above simply means that the identifier Type will stand for a datatype. NB: a_type is not a keyword; it is an identifier that during the execution of the program will represent a single datatype. For example, you could, when defining variables in the class, use the following line:Typea_var;and when the programmer defines which datatype &apos;a_type&apos; is to be when the program instantiates a particular instance of a_class, a_var will be of that type.When defining a function as a member of a templated class, it is necessary to define it as a templated function:template&lt;class Type&gt; void a_class&lt;Type&gt;::a_function(){...} When declaring an instance of a templated class, the syntax is as follows:a_class&lt;int&gt; an_example_class; An instantiated object of a templated class is called a specialization; the term specialization is useful to remember because it reminds us that the original class is a generic class, whereas a specific instantiation of a class is specialized for a single datatype (although it is possible to template multiple types).Usually when writing code it is easiest to precede from concrete to abstract; thereforePrivate:Type variable;Public:{Type funct();}