C++: Function Templates

Function Templates

C++ function templates allow programmers to write functions that are independent of the data types involved. More specifically, they allow programmers to reuse the same code for multiple functions that use different data types. In the video, we gave the max function and the swap function as examples of template functions. Here, we give a function to compute distance:

In the first line, the keyword template signals to the compiler that a list of parameters is to follow. The keyword typename tells the compiler that PData is the name of a data type parameter. Since a data type parameterizes the function, we can call the function with multiple different data type arguments. In this main function, we call the function with int and double argument types.

When the compiler encounters the above function calls, it creates a function for each data type during compilation. The resulting functions are function overloads of the distance function, but they are generated automatically and the programmer need not repeat the code. This helps to reduce errors and improve maintainability. However, it is important to note that this function makes no sense for some data types such as bools.

Function templates can take data type parameters, as we showed in the last example. However, function templates can also take some constant parameters as well. In this next example, we have a function that returns the value of the lowest element in an array:

This function takes two parameters: a data type and a constant int. The data type tells the type of the arguments in the array and the int gives the length of the array.

Given the generic nature of this function, it has wide applicability. We can use the function to find the best time in a list of sprint times or we can use the function to find the best price in a list of hotel prices. The same function applies whether the arrays are arrays of doubles, ints, or anything else. Here, we give an example of the above function being called with two different sets of parameters:

Notice that we have used a parameter list in the function call in this example. In the first example, we could have specified parameters as well, but we did not need to since the compiler could detect the data type automatically. This time, we needed to specify the array size, since the compiler cannot detect that.

In this example, we call the minimum function to find the fastest run times in the list of sprint times. The times are given in integers, presumable hundredths of a second. The second call finds the lowest hotel price. The price list is an array of doubles, which specify the price in dollars, of course. Amazingly, the same function can be used to find the both the hotel price and the sprint time: template functions are extremely powerful.