The Mighty C++ Template - The template (contd.)
(Page 4 of 9 )
Now that we have created the function declaration for our template, lets create the actual code for it. In main.cpp, enter the following code:
#include <iostream>
#include "main.h"
using namespace std;
template<class T> T GetAverage(T num1, T num2, T num3)
{
return static_cast<T>((num1 + num2 + num3) / 3);
}
int main()
{
int x = 10;
int y = 20;
int z = 30;
int returnValue = GetAverage(x, y, z);
cout << "Returned " << returnValue << endl << endl;
return 0;
}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!
Next: A simple class template >>
More C++ Articles
More By Mitchell Harper