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 - The template (Page 3 of 9 )
If youíve ever programmed with Visual Basic, then you will probably be familiar with the variant data type. The variant is type-less in a sense that it allows a variable to be declared as a wild card and contain any type of data.
Well, C++ doesnít allow this, and in many ways, templates can substitute for variants. To fully understand templates, letís start with an example. Open your favourite C++ IDE, and create a new project with two files: main.h and main.cpp. Into main.h, enter the following code:
template<class T> T GetAverage(T num1, T num2, T num3);
This is our template declaration. It looks like a regular function declaration and its purpose is exactly the same as any functions declaration: to let the compiler know that the template exists. Letís break down the templates declaration:
This section of the declaration tells the C++ compiler that we are defining a new template definition. Between the angled brackets, we are declaring a new type identifier, T. This tells the compiler to create a new type identifier called T. T will hold the type of variable that this template will be working with. The type of variable is decided from the types of each of the parameters passed to the function. If, for example num1, num2 and num3 were of type int, then T would be an int.
T GetAverage(T num1, T num2, T num3);
Letís step away from templates for a moment and imagine the following function declaration:
int GetAverage(int num1, int num2, int num3);
Looks similar to our template definition right? Well it is. The T is acting as the type of variable that the template will work with. The template doesnít know what type of variable it can accept yet. As long as the variables passed to the function can handle the operator+ and operator/ (can be added with/divided by other variables) functions (which all numeric types can), then the function will work successfully and will return the sum of all of the numbers divided by three (the average).