Section 23.3 Using the Template Type
In addition to being used for specifying function parameters or return types, the type parameter can also be used within the function body to specify the type of local variables.
Our earlier version of
myMax returned one of the parameters as its result (a > b ? a : b). However, we could also use the template type to declare a local variable to hold the maximum value:
template <typename T>
T myMax(T a, T b) {
T maxVal; // Local variable of type T
if (a > b) {
maxVal = a;
} else {
maxVal = b;
}
return maxVal;
}
If we need to initialize a local variable of the template type, we can do so using the
{} initializer syntax. If applied to a built-in type, this will initialize the variable to zero (or the equivalent for that type). For user-defined types, it will call the no-arg constructor:
template <typename T>
T getDefaultValue() {
T defaultValue{}; // Default-initialize a variable of type T
return defaultValue;
}
We can also use the template parameter to specify type for other templated code. For example, to make a templated function that resets all of the elements of a vector to their default values, we could write:
Some key things to note:
-
On line 7, we specify that the parameter is a
vector<T>&. So this function can be called with a vector of any type and that type will be whatTis deduced to be. -
On line 9, we create an anonymous default value of type
Tusing the{}initializer syntax. That value gets assigned to each element of the vector. -
When applied to the
vector<Time>, ourresetVectorfunction calls the default constructor ofTimefor each element, resulting in all times being reset to12:0.
Checkpoint 23.3.2.
Construct an algorithm to add all the items in a vector of type
T.
You have attempted of activities on this page.
