Chapter 17: Advanced C++ Topics II

Chapter Goals

Templates

Syntax 17.3 Template Class Definition

Syntax 17.3 : Template Class Definition

template<typename type_variable>
class class_name
{

features
};
Example:
template<typename T>
class Pair
{
public:
Pair(T a, T b);
T get_first() const;
T get_second() const;
private:
T first;
T second;
};
Purpose: Define a class template with a type parameter.

Syntax 17.4 Template Member Function Definition

Syntax 17.4 : Template Member Function Definition

template<typename type_variable>
return_type class_name<type_variable>::function_name(parameters) constopt
{

statements
}
Example:
template<typename T>
T Pair<T>::get_first() const
{
return first;
}
Purpose: Supply the implementation of a member function for a class template.

Templates (pairs.cpp)


Exception Handling

Signaling Error Conditions

Syntax 17.8: Throwing an Exception

Syntax 17.8: Throwing an Exception

throw expression;
Example:
throw logic_error("illegal future_value parameter");
Purpose: Abandon this function and throw a value to an exception handler.

Catching Exceptions

Syntax 17.9: Try Block

Syntax 17.9: Try Block

try
{

statements
}
catch (type_name1 variable_name1)
{
statements
}
catch (type_name2 variable_name2)
{
statements
}
...
catch (type_namen variable_namen)
{
statements
}
Example:
try
{
double fvalue = future_value(init, interest, years);
cout << "The future value is " << fvalue << endl;
}
catch(logic_error& e)
{
cout << "Processing error " << e.what() << "\n";
}
Purpose: Provide one or more handlers for types of exceptions that may be thrown when executing a block of statements.

Exception Handling (exception1.cpp)

Exception Handling (exception2.cpp)

Stack Unwinding

Exception Handling (product1.cpp)

Exception Handling (product2.cpp)

Exception Specifications

Syntax 17.10: Exception Specification

Syntax 17.10 : Exception Specification

return_type function_name(parameters)
throw (type_name1, type_name2, ..., type_namen)
Example:
void process_products(fstream& fs)
throw(UnexpectedEndOfFile, bad_alloc)
Purpose: List the types of all exceptions that a function can throw.