Class template Stack
of Section 18.2 used only a type parameter (Fig. 18.2, line 7) in its template declaration. It’s also possible to use nontype template parameters, which can have default arguments and are treated as constants. For example, the C++ standard’s array
class template begins with the template declaration:
template <typename T, size_t N>
(Recall that keywords class
and typename
are interchangeable in template declarations.) So, a declaration such as
array<double, 100> salesFigures;
creates a 100-element array
of double
s class-template specialization, then uses it to instantiate the object salesFigures
. The array
class template encapsulates a built-in array. When you create an array
class-template specialization, the array
’s built-in array data member has the type and size specified in the declaration—in the preceding example, it would be a built-in array of double
values with 100
elements.
We could have used this technique in our GradeBook
class of Section 7.9. Rather than defining static
constants in the class definition’s body to represent the number of students and the number of tests, we could have defined class GradeBook
as a class template with two nontype template parameters, as in
template <size_t students, size_t tests>
class GradeBook {
// class definition's body
};
then used the nontype template parameters’ values throughout the class definition. We ask you to implement this version of class GradeBook
in Exercise 18.14.