Difference between revisions of "intro/function templates"
From cppreference.com
(Created page with "{{title|Function Templates}}") |
|||
Line 1: | Line 1: | ||
{{title|Function Templates}} | {{title|Function Templates}} | ||
+ | |||
+ | There may come a point where we find that set of functions look very similar for different data types. Instead of having multiple duplicates of the same function, we can define a single function using templates that would work with all generic types. | ||
+ | |||
+ | To create a function template we simply add 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 choosen T, but we are free choose whatever we like). Anywhere in the function where T appears, it is replaced with whatever type the function is instantiated for. |
Revision as of 06:43, 5 October 2013
There may come a point where we find that set of functions look very similar for different data types. Instead of having multiple duplicates of the same function, we can define a single function using templates that would work with all generic types.
To create a function template we simply add 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 choosen T, but we are free choose whatever we like). Anywhere in the function where T appears, it is replaced with whatever type the function is instantiated for.