Introduction To C++ Templates and Exceptions
Introduction To C++ Templates and Exceptions
FunctionTemplate
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;
}
TemplateFunction Call
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
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;
class GList_int
{
public: int
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++;
}
…
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
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