One of the biggest advantages of using C++ is templates. Templates were designed from the ground up to allow developers to write one function to handle many different types of parameters. In this article, Mitchell will explain what both function and class templates are, and give examples of each.
We start out by #including the iostream head filer (so we can output to the screen) and our main.h header file, which contains the declaration of our template.
Next, we have the full code for our template:
template<class T> T GetAverage(T num1, T num2, T num3)
return static_cast<T>((num1 + num2 + num3) / 3);
The first line is exactly the same as the templates declaration in main.h. Our template only contains one line, which calculates the average of the three variables passed in as parameters, and returns that value.
Our template uses the static_cast<>() function to make sure that the return value is also of type T. This is necessary, because most of the time, when finding the average, the result will contain a decimal point and mantissa. If, for example, we passed three int values to the template, then we would expect an int to be returned, and not a double, for example. Thatís what the static_cast<>() function is responsible for handling.
Note: The static_cast<>() function is actually a template. The value between the angled brackets tells the template what the return type of the template should be.
Before moving onto the next section, try changing the types and values of x, y, and z. The return type of the template will be the same as the values passed to it!