0% found this document useful (0 votes)
112 views29 pages

Introduction To C++ Templates and Exceptions

This document introduces C++ templates and exceptions. It discusses function templates, class templates, and how to instantiate them. Function templates allow defining functions that work on different data types using template parameters. Class templates allow defining classes that work on different data types. Exception handling allows catching and resolving exceptions using try-catch blocks. Exceptions represent errors or unexpected events. The document provides examples of function templates, class templates, and using try-catch blocks to handle exceptions like dividing by zero.

Uploaded by

jyoti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views29 pages

Introduction To C++ Templates and Exceptions

This document introduces C++ templates and exceptions. It discusses function templates, class templates, and how to instantiate them. Function templates allow defining functions that work on different data types using template parameters. Class templates allow defining classes that work on different data types. Exception handling allows catching and resolving exceptions using try-catch blocks. Exceptions represent errors or unexpected events. The document provides examples of function templates, class templates, and using try-catch blocks to handle exceptions like dividing by zero.

Uploaded by

jyoti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

Introduction to

C++ Templates and Exceptions

 C++ Function Templates


 C++ Class Templates

 Exception and Exception Handler


C++ Function Templates
 Approaches for functions that implement
identical tasks for different data types
 Naïve Approach
 Function Overloading
 Function Template

 Instantiating a Function Templates


Approach 1: Naïve Approach
 create unique functions with unique
names for each combination of data
types

 difficult to keeping track of multiple


function names
 lead to programming errors
Example
void PrintInt( int n )
{
cout << "***Debug" << endl;
cout << "Value is " << n << endl;
}
void PrintChar( char ch )
{
cout << "***Debug" << endl;
cout << "Value is " << ch << endl;
}
void PrintFloat( float x ) To output the traced values, we insert:
{
… PrintInt(sum);
}
void PrintDouble( double d ) PrintChar(initial);
{
… PrintFloat(angle);
}
Approach 2:Function Overloading
(Review)
• The use of the same name for different C++
functions, distinguished from each other by
their parameter lists

• Eliminates need to come up with many


different names for identical tasks.
• Reduces the chance of unexpected results
caused by using the wrong function name.
Example of Function Overloading
void Print( int n )
{
cout << "***Debug" << endl;
cout << "Value is " << n << endl;
}
void Print( char ch )
{
cout << "***Debug" << endl;
cout << "Value is " << ch << endl;
}
void Print( float x ) To output the traced values, we insert:
{
Print(someInt);
} Print(someChar);
Print(someFloat);
Approach 3: Function Template
• A C++ language construct that allows the compiler
to generate multiple versions of a function by
allowing parameterized data types.

FunctionTemplate

Template < TemplateParamList >


FunctionDefinition

TemplateParamDeclaration: placeholder

class typeIdentifier
typename variableIdentifier
Example of a Function Template
Template parameter
template<class SomeType>
(class, user defined
void Print( SomeType val ) type, built-in types)
{
cout << "***Debug" << endl;
cout << "Value is " << val << endl;
}

Template To output the traced values, we insert:


argument Print<int>(sum);
Print<char>(initial);
Print<float>(angle);
Instantiating a Function
Template
• When the compiler instantiates a template,
it substitutes the template argument for the
template parameter throughout the function
template.

TemplateFunction Call

Function < TemplateArgList > (FunctionArgList)


Summary of Three Approaches

Naïve Approach Function Overloading


Different Function Definitions Different Function Definitions
Different Function Names Same Function Name

Template Functions
One Function Definition (a function template)
Compiler Generates Individual Functions
Class Template
• A C++ language construct that allows the compiler
to generate multiple versions of a class by allowing
parameterized data types.

Class Template

Template < TemplateParamList >


ClassDefinition

TemplateParamDeclaration: placeholder

class typeIdentifier
typename variableIdentifier
Example of a Class Template
template<class ItemType>
class GList
{ Template
public: parameter
bool IsEmpty() const;
bool IsFull() const;
int Length() const;
void Insert( /* in */ ItemType item );
void Delete( /* in */ ItemType item );
bool IsPresent( /* in */ ItemType item ) const;
void SelSort();
void Print() const;
GList(); // Constructor
private:
int length;
ItemType data[MAX_LENGTH];
};
Instantiating a Class Template
• Class template arguments must be
explicit.
• The compiler generates distinct class
types called template classes or
generated classes.
• When instantiating a template, a
compiler substitutes the template
argument for the template parameter
throughout the class template.
Instantiating a Class Template
To create lists of different data types
// Client code
template argument
GList<int> list1;
GList<float> list2;
GList<string> list3;

list1.Insert(356); Compiler generates 3


list2.Insert(84.375); distinct class types
list3.Insert("Muffler bolt");
GList_int list1;
GList_float list2;
GList_string list3;
Substitution Example

class GList_int
{
public: int

void Insert( /* in */ ItemType item );


int
void Delete( /* in */ ItemType item );

bool IsPresent( /* in */ ItemType item ) const;

private: int
int length;
ItemType data[MAX_LENGTH];
};
int
Function Definitions for
Members of a Template Class
template<class ItemType>
void GList<ItemType>::Insert( /* in */ ItemType item )
{
data[length] = item;
length++;
}

//after substitution of float


void GList<float>::Insert( /* in */ float item )
{
data[length] = item;
length++;
}
Another Template Example:
passing two parameters

template <class T, int size>


class Stack {...
non-type parameter
};
Stack<int,128> mystack;
Exception
• An exception is a unusual, often
unpredictable event, detectable by
software or hardware, that requires
special processing occurring at runtime
• In C++, a variable or class object that
represents an exceptional event.
Handling Exception
• If without handling,
• Program crashes
• Falls into unknown state
• An exception handler is a section of program
code that is designed to execute when a
particular exception occurs
• Resolve the exception
• Lead to known state, such as exiting the
program
Standard Exceptions
 Exceptions Thrown by the Language
– new
 Exceptions Thrown by Standard
Library Routines
 Exceptions Thrown by user code,
using throw statement
The throw Statement
Throw: to signal the fact that an
exception has occurred; also called
raise

ThrowStatement throw Expression


The try-catch Statement
How one part of the program catches and processes
the exception that another part of the program throws.
TryCatchStatement
try
Block
catch (FormalParameter)
Block
catch (FormalParameter)
FormalParameter
DataType VariableName


Example of a try-catch Statement
try
{
// Statements that process personnel data and may throw
// exceptions of type int, string, and SalaryError
}
catch ( int )
{
// Statements to handle an int exception
}
catch ( string s )
{
cout << s << endl; // Prints "Invalid customer age"
// More statements to handle an age error
}
catch ( SalaryError )
{
// Statements to handle a salary error
}
Execution of try-catch
A No
statement throws statements throw
an exception an exception

Control moves Exception


directly to exception
handler
Handler

Statements to deal with exception are executed

Statement
following entire try-catch
statement
Throwing an Exception to be
Caught by the Calling Code
void Func3()
{

try
{ void Func4()
Function
{
call
Func4();
Normal if ( error )
} return throw ErrType();
catch ( ErrType )
{ }

}
Return from
thrown
}
exception
Practice: Dividing by ZERO
Apply what you know:
int Quotient(int numer, // The numerator
int denom ) // The denominator
{
if (denom != 0)
return numer / denom;
else
//What to do?? do sth. to avoid program
//crash
}
A Solution

int Quotient(int numer, // The numerator


int denom ) // The denominator
{
if (denom == 0)
throw DivByZero();
//throw exception of class DivByZero
return numer / denom;
}
A Solution
// quotient.cpp -- Quotient program while(cin)
{
#include<iostream.h> try
{
#include <string.h> cout << "Their quotient: "
int Quotient( int, int ); << Quotient(numer,denom) <<endl;
class DivByZero {}; // Exception class }
catch ( DivByZero )//exception handler
int main()
{
{
cout<<“Denominator can't be 0"<< endl;
int numer; // Numerator }
int denom; // Denominator // read in numerator and denominator
}
//read in numerator return 0;
and denominator }
Take Home Message
 Templates are mechanisms for generating functions and
classes on type parameters. We can design a single class
or function that operates on data of many types
– function templates
– class templates

 An exception is a unusual, often unpredictable event that


requires special processing occurring at runtime
– throw
– try-catch

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy