Namespaces
Variants
Actions

Function Templates

From cppreference.com
Revision as of 06:59, 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.

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.

#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);
}