C + + Learning Note 16-templates and generics programming (i)

Source: Internet
Author: User

Templates and generics programming


First, the template definition

1. Define the function template:
A. The template definition starts with the keyword template, followed by a template parameter list, which is a comma-delimited table of one or more template parameters that are enclosed in angle brackets. The template parameter list cannot be empty.
B.A template parameter can be a type parameter that represents a type, or it can be a non-type parameter that represents a constant expression. A non-type parameter is followed by a type specifier, and the type parameter is defined after the keyword class or typename, for example, class T is a type parameter named T, where class and TypeName are not different.

2.inline function Template: The inline specifier is placed after the template parameter list and cannot be placed before the keyword template until the type is returned.
Template <typename t> inline T min (const t&,const t&);

3. Class Template: The class template is also a template, so you must start with the keyword template, followed by the templated parameter list.
When you use a class template, you must explicitly specify an argument for the template parameter. The compiler uses arguments to instantiate a specific type version of this class.

4. Template parameters:
A. Like function parameters, the name that a programmer chooses for a template parameter has no intrinsic meaning.
B. The only meaning that can be given to a template parameter is whether the differential parameter is a type parameter or a non-type parameter. If it is a type parameter, we know that the parameter represents an unknown type, and if it is a non-type parameter, we know it is an unknown value.


5. Template parameter scope:

A. The name of a template parameter can be used after it is declared as a template parameter until the end of the template declaration or definition.
B. Template parameters follow the regular name masking rules. A template that has the same name as the object, function, or type declared in the global scope is masked by the global name.
c. Restrictions on the use of template parameter names: Names used as template parameters cannot be reused inside templates (they cannot be used again as types).
template <class t> T calc (const T &a, const T &b)
{
typedef double T; Error:redeclares template parameter T
T tmp = A;
// ...
return TMP;
}
D. This restriction also means that the name of a template parameter can only be used once in the same template parameter list:
//Error:illegal reuse of template parameter name V
Template <class V, class v> v Calc (const v&, const v&);
E. Of course, just as you can reuse function parameter names, the names of template parameters can be reused in different templates.
F. The name of the template parameter does not have to be the same in the declaration and definition of the same template.
//All three uses of Calc refer to the same function template
Forward declarations of the template
Template <class t> T calc (const t&, const t&);
Template <class u> U calc (const u&, const u&);
Actual definition of the template
Template <class type>
Type Calc (const type& A, const type& b) {/* ... */}
G. Each template type parameter must be preceded with the keyword class or typename, each non-type parameter must precede the type name, omitting the keyword or the type specifier is wrong

The difference between 6.typename and class:
In the function template formal parameter list, the keyword TypeName and class have the same meaning, can be used interchangeably, two keywords can be used in the same template parameter list

7. Prefix the member name with the keyword typename to tell the compiler to treat the member as a type.
Template <class Parm, class u>
Parm FCN (parm* array, U value)
{
TypeName Parm::size_type * p; Ok:declares p to be a pointer
}

8. Non-type template parameters:
A. When calling a function, a non-type arguments is substituted with a value, and the type of the value is specified in the template parameter list.
B. The template non-type parameter is a constant value inside the template definition, and when a constant expression is required, you can specify the length of the array using a non-type parameter (for example, as you did here).

9. Write a generic program:
A. Actions done inside the function template limit the types that can be used to instantiate the function.
B. When writing template code, it is useful to have as few requirements as possible for an argument type.
C. Two important principles for writing generic code:
The template's formal parameter is a const reference. The tests in the function body are only used for < comparisons.

Second, the instantiation of
1. Instantiation of the class:
A. Each instantiation of a class template results in a separate class type. A queue that is instantiated for an int type has no relation to any other queue type and has no special access rights to other queue type members.
B. To use a class template, you must explicitly specify a template argument.
queue<int> qi;//Ok:defines Queue that holds ints
Types defined with a template class always contain template arguments. For example, a Queue is not a type, and queue<int> or queue<string> is a type.

2. Instantiation of Function Templates:
When using a function template, the compiler usually infers the template arguments for us:
int main ()
{
Compare (1, 0); Ok:binds template parameter to int
Compare (3.14, 2.7); Ok:binds template parameter to double
return 0;
}
3. Restricted Conversions for arguments of type parameters: Generally speaking, arguments are not converted to match an existing instantiation, instead, a new instance is generated. In addition to generating a new instantiation, the compiler performs only two conversions:
A.const conversion: A function that accepts a const reference or a const pointer can be called by a reference or a pointer to a non-const object, without creating a new instantiation. If a function accepts a non-reference type, the parameter type argument ignores const, that is, the same instantiation is used regardless of whether a const or non-const object is passed to a function that accepts a non-reference type.
B. Array or function-to-pointer conversions: If the template parameter is not a reference type, then the regular pointer conversion is applied to an argument of the type of the group or function. The array real arguments is treated as a pointer to its first element, and the function argument is treated as a pointer to the function type.

4. The limit for type conversions applies only to those arguments whose type is a template parameter.
A formal parameter defined with a normal type can use a regular conversion, and the following function template sum has two parameters:
template <class type> type sum (const Type &OP1, int op2)
{
return OP1 + op2;

}


5. Template argument inference and function pointers: You can use a function template to initialize or assign a function pointer, so that when you do this, the compiler uses the type of the pointer to instantiate the template version with the appropriate template arguments. When you get the address instantiated by a function template, the context must be this: it allows you to determine a unique type or value for each template parameter.

//overloaded versions of Func; each take a different function pointer type
void func (Int (*) (const string&, const string&));
void func (Int (*) (const int&, const int&));
Func (Compare); Error:which instantiation of compare?


6. Use a type parameter in the return type:

A. One way to specify a return type is to introduce a third template parameter, which must be explicitly specified by the caller, that is, the return type cannot be inferred, and must display the specified:
T1 cannot is deduced:it doesn ' t appear in the function parameter list
Template <class T1, class T2, class t3>
T1 sum (T2, T3);
B. Explicit template arguments match the template parameters from left to right, the first template actually participates in the first template parameter match, the second one participates in the second parameter match, and so on. If you can infer from a function parameter, the explicit template argument of the end (rightmost) parameter can be omitted.

7. Pointers to explicit real-life participation in function templates: You can eliminate ambiguity by using explicit template arguments:
Template <typename t> int compare (const t&, const t&);
overloaded versions of Func; Each take a different function pointer type
void func (Int (*) (const string&, const string&));
void func (Int (*) (const int&, const int&));
Func (compare<int>); ok:explicitly Specify which version of compare

C + + Learning Note 16-templates and generics programming (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.