function templates
Role
There are many times when the type of the parameter and the type of the return value is variable, and we define the template to make the function more flexible to use.
We design a comparison function, if we can compare the two parameters are int, two parameters may be string type, separate design two comparison function will be more cumbersome, at this time, we use the function template.
Template<typename t>
int cmp (t A, T b) {
Return a>b;
}
(1) Each time a call is made, the compiler infers the template parameters to instantiate a specific version of the function for us, and T can be replaced with any type.
(2) The template can be replaced by class, and the function of two is the same.
Class template
Defining class Templates
The definition of a class template is similar to that of a template function, but it is slightly different when declaring an object
Template<typename T>class gg{
Public:
T A;
GG (T aa): A (AA) {};
};
Gg<string> g ("ASA"); Declarations section
Non-type template parameters
In addition to defining type parameters, you can define non-type parameters in a function, and a non-type parameter represents a value rather than a type.
For example
Template<typename T, unsigned n>class gg{
Public:
T A;
GG (T aa): A (AA) {};
int aa ();
};
Inline and constexpr function templates
As with normal defined functions, the inline or constexpr is written before the function body type after the template.
member functions for class templates
Template<typename T, unsigned n>//= Next is a template
int gg<t, N>::AA () {//through gg<t, n> find the class corresponding to the function
for (int i = 0;i < n; i++) printf ("gaofangzuishuai\n");
return A;
}
HLW's C + + learning Notes template and generic programming