C ++ template Summary (1/2)
STL is a classic of C ++ generic programming (GP), and the template syntax supported by the language is the basis for generic programming. Generic programming is implemented in C ++.Polymorphism during compilationIs the most important way. This section summarizes the template-related points of the C ++ language as the basis for a deep understanding of the idea of generic programming.
The so-calledA template is a blueprint or formula used to create a class or function.. From the abstract level
-Classes have the same or similar characteristics for the same category in the real world.An abstraction of a real objectDefines related data members and provides related operation interfaces. Class instantiation is used to represent real objects in the real world for software modeling, which greatly reduces code duplication.
-Templates are identical or similar.A high-level abstraction of A ClassThe type parameters used by the template represent these classes. They may have similar functions or have similar members. By instantiating a specific type, a class is created, this also greatly reduces code duplication.
Definition)
The template definition starts with the keyword template, followedTemplate parameters, Including one or more brackets (separated by commas)Template parameters. The template parameters start with the typename or class keyword. The class is used in the old C ++, And the typename is added later. There is no difference between the two.
Function template definition:
template
int cmp(const T & a, const T & b){ if (a < b) return -1; else if (b < a) return 1; else return 0;}
Class template definition:
template
class Stack{... void push(const T & );...};template
void Stack
::push(const T &v){ ...}
After the template class declaration is complete, the class name is changed to ClassName <T>. Therefore, when defining a member function outside the class, you must use the above syntax to declare the domain parsing operator.
Template parameters: The moment is treated as a type. A name for the generalized type is similar to the form parameter in the function declaration. It also follows the identifier naming principle and can be specified at Will or multiple. You also need to follow the rules of the shape parameter scope to block the declaration of the same name type outside the template class or template function. A template parameter is a type rather than a parameter variable called by a function. Therefore, if you use typedef to re-declare a type with the same name in the template class or template function, a redeclare error will occur. The template parameter is a generalized type, so it is best to make the least assumptions about the operations supported by this type of code. In the preceding function template definition, we only assume that the type T supports the operator <operator.
Template type parameters:
The template type parameters are the parameters specified by typename or class. This requires that a specific type be specified during the instantiation phase before the compiler can create a specific class. At this time, if a class defines a type member, if the class name + scope resolution operator is directly used for access, the compiler will act as a data member by default, and must use the typename display to inform the compiler to act as a type member.
template
void fun(A * a){... typename A::ref_type p;...}
The preceding definition assumes that generic class A defines type members.ref_typeWhen using A type member in A template function or template class, you must usetypenameOtherwise, the compiler willref_typeTreated as A data member of.
Non-type parameters of the template:
The template parameters are not necessarily generic, but can be of a specific type. This is a constant value within the template definition. When a constant expression is required, you can use a non-type parameter.
template
class Array{private: T arr[n];public: explict Array(const T &v); ...};
Here, the non-type parameter is specified as a specific int type, and parameter n is a constant defined in the template, which can be used as the size of the arr array of the data member. Therefore, non-type template parameters have the following restrictions:
-Non-type parameters can only be integer, enumeration, reference, and pointer.
-The values of non-type parameters cannot be modified inside the template definition, and their addresses cannot be used (n ++, & n, and other operations are not allowed), because they must be treated as constants.
-A constant or constant expression must be used for template instantiation.
For the Array template class defined above, the Array arr declared with automatic variables maintains the memory stack, compared with the heap memory managed by the new/delete using the dynamically passed Array size in the constructor, the execution speed is faster, which is more obvious for small arrays with frequent operations. However, there is a drawback that the array compiler of each size will re-generate an independent class. In addition, the dynamic allocation method using constructors is more common, you can assign values between arrays of different sizes.
Default template parameters
When you use a template-type parameter, you can follow the default function rule to provide the default value for the template-type parameter. The default value is a specific type and must be placed after a non-default parameter. However, the default value cannot be used for non-type template function parameters.
template
class M{...};M
c1; //c1 is M
M
c2; //c2 is M
For non-type parameters, default values can be used for template classes and functions.
template
class Array{private: T arr[n];...};
Instantiation class template instantiation
The class template itself is a class abstraction. It describes behavior in a generic way. It must be instantiated before the compiler can create the corresponding class to create and use the object of the corresponding class. The process that the compiler uses a template to generate instances of a specific type of a specified class or function is called Instantiation. It can be classified into implicit instantiation and display instantiation.
Stack
Ss; // implicit template class Stack
; // Display the declaration of a Stack
Class
When the class object is declared in implicit instantiation, the template parameter is specified at the same time. If the template parameter is displayed as the parameter, the template class is instantiated without defining the class object.
After instantiating the template parametersStack As a class instantiated from the template, all operations related to the class are treated as a whole. Default parameters can be omitted or specified separately.
For non-type parameters of a template, constants or constant expressions must be used for instantiation. Otherwise, the compiler cannot pass.
Array
arrd;
Function template real parameter Inference
For a function template, the compiler automatically instantiates a function of the corresponding type based on the type of the arguments passed by calling the function. This process is called template argument deduction ). This is fully used in the traits programming techniques in STL.
cmp(1, 11);cmp(1.2, 2,4);
The two calls instantiate two functions respectively:
int cmp(const int & a, const int & b){ if (a < b) return -1; else if (b < a) return 1; else return 0;}int cmp(const double & a, const double & b){ if (a < b) return -1; else if (b < a) return 1; else return 0;}
During inference, the real parameters of multiple parameters must be completely matched. For example, a function is generated for each type. A compilation error occurs if a matching error occurs. In addition, when real parameters are prompted for conversion when a common function is called, the matching of the template function does not convert the real parameters, but re-instantiates the function to generate a new function. The Compiler only performs two conversions:
-Const Conversion: Functions that receive const references or const pointers can be called by using non-const object references or pointers, without new instantiation. For a non-reference type parameter, the const that participates in the real parameter is ignored.
-Array or function to pointer Conversion: If the template parameter is not of the reference type, the regular pointer conversion is applied to the real parameters of the array or function type. The array is used as the pointer to the first element, and the real parameters of the function are used as the pointer to the function type.
Template
T f1 (T, T); template
T f2 (const T &, const T &); string s1 ("s1"); const string s2 ("const s2"); f1 (s1, s2 ); // call f1 (string, string) to ignore constf2 (s1, s2); // convert s1 to const to reference int a [10], B [20]; f1 (a, B); // when f1 (int *, int *) is called, it is regarded as the pointer to the first element f2 (a, B); // call failed, the two arrays referenced by the reference type are not of the same size and the type does not match.
In addition, you can use the template function to initialize the function pointer. At this time, the compiler will use the type declared by the function pointer as the template real parameter to instantiate the template function:
template
int cmp(const T&, const T&);int (*pf) (const int &, const int &) = cmp;
Show real parameters:
When the types of function return values are different from those in the form parameter table, you need to use the display real parameters to solve this problem:
temp1ate
Tl sum(T2 , T3);temp1ate
T3 a1ternative_sum(T2 , Tl);
The input T2 and T3 types are unknown, and the type of the return value cannot be determined after the sum. Therefore, the return type is also specified as the template parameter. In this case, the return type cannot be specified only when the sum function is called for real parameter inference. Therefore, you need to specify the display. Using the display template real parameter list syntax, the compiler matches from left to right, and finally matches the real parameter type in sequence. Call method:
long va13 = sum
(1, 10L);long va12 = a1ternative_sum
(1 , 10L);
Now, we will summarize the class template members, member templates, and special templates.