Skip to main content

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:
Listing 23.3.1.
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:
Listing 23.3.2.
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:
Listing 23.3.3.
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 what T is deduced to be.
  • On line 9, we create an anonymous default value of type T using the {} initializer syntax. That value gets assigned to each element of the vector.
  • When applied to the vector<Time>, our resetVector function calls the default constructor of Time for each element, resulting in all times being reset to 12:0.
You have attempted of activities on this page.