This tutorial covers the basics of using function templates in C++. It shows you how to create them and explains how they work.
What are function templates used for?
Suppose you have a function that returns the sum of two numbers stored in two variables. The variables are passed as parameters (arguments).
The parameters are of type int, so the function would look like this:
#include "stdafx.h"
// Uncomment the below line if you don't use managed C++
//#include
// Function definition
void Add(int a, int b)
{
   System::Console::WriteLine(a + b);
}
int main()
{
   // Call to the function
   Add(5, 2);
   return 0;
}
But what if I want to add two doubles? The function accepts only int’s, what can I do? Well here the function template comes into play.
#include "stdafx.h"
// Uncomment the below line if you don't use managed C++
//#include
// Function template
template <typename AnyType>
// Function definition
void Add(AnyType a, AnyType b)
{
   System::Console::WriteLine(a + b);
}
int main()
{
   // Call to the function
   Add(5.6, 3.3);
   return 0;
}
Probably you already know what this code does and how function templates work. The first thing you noticed is perhaps the following line:
// Function template
template <typename AnyType>
This line creates a – let’s say -universal type called AnyType.
Older versions of C++ don’t understand the template so instead of typename you have to use the keyword class, like this:
// Function template
template <class AnyType>
Moving on into the code you can see that we replaced the int parameters of the function with AnyType:
// Function definition
void Add(AnyType a, AnyType b)
Now depending on which parameters we will pass to the Add() function, AnyType will change to the type that fits the parameters.
For example if we pass ints, the AnyType keyword will be replaced with int. But if we pass doubles like we did, AnyType will become double:
// Because we passed doubles, AnyType will become double
Add(5.6, 3.3);
So now you know that the actual use of function templates is to pass diferent types of variables to the same function, using function calls, like this:
#include "stdafx.h"
// Uncomment the below line if you don't use managed C++
//#include
// Function template
template <typename AnyType>
// Function definition
void Add(AnyType a, AnyType b)
{
   System::Console::WriteLine(a + b);
}
int main()
{
   // AnyType will be int
   Add(5, 2);
   // AnyType will be double
   Add(5.6, 3.3)
   return 0;
}
Function templates improve performance?
No, using function templates you don’t get any improved performance. For example in the code above the compiler will actually create two versions of the function, one with int parameters and one with double. The only gain is the programmer’s time.