Namespaces
Variants
Actions

Difference between revisions of "intro/function templates"

From cppreference.com
Line 33: Line 33:
  
 
We created a function template called {{c|print}} which is called in the {{c|int main}}. The first variable we pass into the function is an {{c|int}}, we then call the {{c|print}} function again, but this time passing in a {{c|double}}.
 
We created a function template called {{c|print}} which is called in the {{c|int main}}. The first variable we pass into the function is an {{c|int}}, we then call the {{c|print}} function again, but this time passing in a {{c|double}}.
 
{{example
 
|code=
 
#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
 
}}
 

Revision as of 07:17, 5 October 2013


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.