Namespaces
Variants
Actions

Function Templates

From cppreference.com
Revision as of 07:12, 5 October 2013 by Ht (Talk | contribs)


There may come a point where we find that a set of functions look very similar for different data types. Instead of having multiple duplicates of the same code, we can define a single function using templates that would work with all generic data types.

Defining a function template

We define a function template by adding template<typename T> before the function to tell the compiler that what follows is a template, and that T is a template parameter that identifies a type (In this example we have chosen T, but we are free to choose whatever we like). Anywhere in the function where T appears, it is replaced with whatever type the function is instantiated for. Take the following example:

#include <iostream>
 
template<typename T>
void print(T x)
{
	std::cout << "value = " << x << std::endl;	
}
 
int main()
{
	int a = 5;
	double b = 2.42;
 
	print(a);
	print(b);
}

Output:

value = 5
value = 2.42

We created a function template called print which is called in the int main. The first variable we pass into the function is an int, we then call the print function again, but this time passing in a double.