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.
The Mighty C++ Template - A simple class template (contd.) (Page 6 of 9 )
Open classtemplate.cpp and enter the following code:
#include <iostream>
#include "classtemplate.h"
using namespace std;
template<typename T> T MyClass<T>::GetAverage()
{
return static_cast<T>((n1 + n2 + n3) / 3);
}
int main()
{
MyClass<int> mc(1, 2, 3);
cout << "Return value is: " << mc.GetAverage() << endl << endl;
return 0;
}
Lets start by describing the GetAverage function of the MyClass class.
template<typename T> T MyClass<T>::GetAverage()
{
return static_cast<T>((n1 + n2 + n3) / 3);
}
Firstly, our class function is declared as a template using the template<typename T> keywords, meaning that our class function has just one type identifier, T.
T MyClass<T>::GetAverage()
Secondly, our class function returns a value of type T. Notice that the class name, “MyClass”, is followed by our type parameter, T. This tells the C++ compiler that our function will handle values of type T.
The code for our class function is similar to the code for our template function, from above:
return static_cast<T>((n1 + n2 + n3) / 3);
All of the three privately declared variables, n1, n2 and n3 are summed up, divided by three and then returned as a variable of type T.