Question: Activity 14-2 - Templates for Classes The syntax for class templates is basically the same as that for function templates: template This statement will be
Activity 14-2 - Templates for Classes
The syntax for class templates is basically the same as that for function templates:
template
This statement will be placed before the template definition. The type parameter T is used in the class definition just like any other type. Here is an example:
// Class for a pair of values of type T: template
T_get_element(int position) const;
private: T first; T second;' };
An object of this class contains a pair of values of type T. Once the class template is defined, we can declare objects of this class. The declaration must specify what type is to be filled in for T. For example,
Pair
The two objects can be used like any other objects. For example,
score.set_element(1, 3); // Sets the score for the first team to 3 score.set_element(2, 0); // Sets the score for the second team to 0
As you can see in the above class member function definitions are also templates.
Here are the definitions for the member functions set_element and the constructor Pair with two arguments.
// Use iostream and cstdlib template
template
Important note: The class name before the scope resolution operator is Pair
The name of a class template may be used as the type for a function parameter:
For example, int add_up(const Pair
returns the sum of the two integers in the_pair. You can use a class template within a function template.
template
Type Definitions You can specialize a class template by giving a type argument to the class name, as in the following example:
Pair
The specialized class name, like Pair
typedef Class_Name
The type name PairOfInt can now be used to declare objects of type Pair
PairOfInt pair1, pair2;
The type name PairOfInt can also be used to specify the type of a formal parameter.
******Exercise 14.2 Write the definitions for the member functions get_element for the class template Pair and the constructor Pair( ) with no argument. Add to the class a member function called display_pairs that displays the pairs. Then write a complete program that uses the class to read a pair of integers and a pair of strings and assign them to the appropriate objects, grades and names. Here is an example of an input pair: first pairs: 87 90 second pairs: Tom Martha
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
