function templates are generic function descriptions, that is, they use generics to define functions, where generics can be replaced by specific types, such as int or double. Passing a type as an argument to a template enables the compiler to generate a function of that type.
Function templates allow you to define functions in any type of way. For example, you can create a template for a swap function like this:
Template <typename t>void Swap (t &a, t &b) {T temp;temp = A;a = B;b = temp;}
The template does not create any functions, but simply tells the compiler how to define the function. The above code keyword typename and keyword class are all possible, but the keyword typename is recommended.
To let the compiler know that the program needs a specific form of exchange function, you only need to use the swap () function in your program. The compiler checks the type of parameter used and generates the appropriate function.
#include <iostream>template <typename t>void Swap (t &a, t &b); using namespace Std;int main () {int i = 1 0;int j = 20; Swap (i, j); cout << "i =" << i << endl;cout << "j =" << j << endl;double x = 24.5;dou ble y = 30.7; Swap (x, y); cout << "x =" << x << endl;cout << "y =" << y << endl;return 0;} Template <typename t>void Swap (t &a, t &b) {T temp;temp = A;a = B;b = temp;}
The function template cannot shorten the executable program, such as the above code, will still be defined by two separate functions, and the final code does not contain any templates, but contains only the actual function generated by the program. The advantage of using templates is that it makes it easier and more reliable to build multiple function definitions.
However: the same function template , only applies to the function of the same number of parameters and different types, and the same function body, if the number of arguments is different, you cannot use the function template. However, you can overload a function template.
Http://www.cnblogs.com/lidan/archive/2012/02/04/2338677.html
C + + function templates