C + + Primer Chinese version of Learning notes (15) __c++

Source: Internet
Author: User
Tags function definition

16th chapter template and generic programming

1

2 function templates

Template<typename t>

int compare (const T &v1,const t &v2) {}//template parameter cannot be empty

3 class Templates

Template<class type>

Class queue{

Public

Queue ();

Private

//

}

4 non-type template parameter examples allow you to pass a reference parameter that points to an array of any size

Template<class T, size_t n>

void Array_init (T (&parm) [N])

{

for (Size_ti = 0; I!= N; ++i) {

parm[i]= 0;

}

}

function template to determine the length of an array:

Template<class t,size_t n>

std::size_t size (t (&parm) [N])

{

Return N

}

1 explicit arguments for template functions

Template<class T1,class T2,class t3>

T1 sum (T2, T3)

2 Template Compilation Model

A to include the compilation model, the compiler must see the definition of all the templates used. #include "xx.cc"

b) Compile the model separately, and the compiler tracks the related template definitions. Export, specifying that the definition may be instantiated in other files

3 when used with C-style strings, template specificity may be required.

4 generic programming is code that is written in a way that is independent of any particular type. When using a generic program, we need to provide the type and value of the specific program instance. and depend on some form of polymorphism.
Polymorphism in object-oriented programming is applied at runtime to classes that have inheritance relationships, and we are able to write code that uses these classes, ignoring differences between the base class and the derived class
In addition, the polymorphism that object-oriented programming relies on is called Run-time polymorphism, and the polymorphism that the generic program relies on is called compile-time polymorphism or parametric polymorphism.

5 function Template: A function independent of the type, which can be used as a way to produce a specific type version of a function.
The format is defined as:
Equivalent to
Function templates can be declared as inline in the same way as a template function. Specifier is placed after the template parameter list, before returning the type, not before the keyword template

6 The syntax of template parameters:

The name of the template parameter can be used after the declaration is declared as a stencil parameter until the end of the stencil declaration or definition.

Ii. a name used as a template parameter cannot be reused within a model. This restriction means that the name of the template parameter can only be used once in the same profile parameter list

Iii. to any other function or class, a template can be declared but not defined. The declaration must indicate that the function or class is a template.

7 Specify the type internally in the template definition:

By adding a keyword typename to the member name, tell the compiler to treat the member as a type. If not, the compiler assumes that the name specifies the data member rather than the type.
It is a good idea to specify that a name is a type if you are unsure whether you need to typename it.

8 template non-type parameters are constant values that are inside the template definition. You can use an untyped parameter when you want a constant expression.
The operations done inside the function template limit the types that can be used to instantiate the function. The responsibility of the programmer is to ensure that the type used as a function argument actually supports any operation used, and that those operations are working properly in an environment where the template uses those operations.
When we write the template code, it is useful to have as few requirements as possible for the argument type.

9 Two important principles for writing generic code:

A the formal parameter of the template is a const reference

b) The test in the function body is only < comparison

In general, when compiling a template, the compiler may identify errors in three phases:
The first stage is the compilation of the template definition itself. In this phase, the compiler can not find many errors, you may detect a class of grammatical errors such as missing a good or bad spelling of a variable name

The second error detection event is when the compiler sees the template used, at this stage, the compiler still does not have a lot of checks to do. Check only the number and type of arguments are appropriate

The third time, when instantiated, does not know much about the effectiveness of the program. Similarly, a compilation error may even occur after each file that uses the template has been successfully compiled. Only a few cases of errors are detected during instantiation, and error detection may occur at the time of the connection.

Each instantiation of the 15 class template produces a separate class type. A function (or class) that is instantiated for an int type has no relationship to other functions (or classes) and has no special access to other functions (or classes).

16   Fan Ben Shi parameter inference:
Arguments for multiple type parameters must exactly match the restricted conversion of the arguments of the
 
type parameter:
   Generally, the arguments are not converted to match an existing instantiation, Instead, a new instance is generated. In addition to creating new instantiations, the compiler performs only two conversions: the
        const conversion: A function that accepts a const reference or a const pointer can be invoked separately with a reference or pointer to a non-const object, without instantiating it. If the function accepts a unreferenced type, the parameter types and arguments ignore the const, that is, whether a const or non-const object is passed to a function that accepts an unreferenced type , both use the same instantiated
       array or function to the pointer conversion: If the template parameter is not a reference type, The arguments for an array or function type apply a general pointer conversion. The real arguments of arrays is treated as a pointer to its first element, and a function argument is treated as a pointer to a function type.
       General conversions applied to non-template arguments: The restriction of type conversions applies only to those arguments whose class correlation is a template parameter.

      template argument inference and function pointers: You can initialize or assign a function pointer using a function template, in which case the compiler uses the type of the pointer to instantiate the template version with the appropriate template arguments.
       get the address of a function template instantiation, the context must be this: it allows you to determine a unique type or value for each template parameter.

17 Display arguments for the function template:
To specify an explicit template argument:
A type parameter is used in a return type, and one way to specify a return type is to introduce a third template parameter, which must be indicated by the caller.

Just be aware of a problem: a type that has no arguments can be used to infer the type, instead, the caller must explicitly provide the argument for that parameter each time the fun is invoked.
Explicit template arguments match the corresponding template parameters from left to right. If you can infer from a function parameter, only the explicit template arguments for the end parameter can be omitted. This is similar to the calling rule for overloaded functions.

In this example, the type is initialized, but since Type2 uses a type that must be explicitly given, we cannot just use it at the time of the call, but only the entire parameter must explicitly specify the argument.
Displays a pointer to the actual participating function Template: This eliminates ambiguity.

18 when the compiler sees the template definition, it does not immediately generate code. The compiler produces a template argument with a specific type only when the template is used, such as when the function target is invoked or when the class template object is defined.
Special case of Template compilation: To be instantiated, the compiler must be able to access the source code that defines the template. When you call a function template or a member function of a class template, the compiler requires a function definition that requires code that is usually placed in the source file.

Two models defined for compiling template code in C + +:
Contains the compilation model: at compile time, the compiler must see the definition of all the templates used. You can generally put the header file used, the template definition in conditional compilation.
Compile the model separately: the compiler will track the relevant template definitions for us. But we have to let the compiler know that to remember the given template definition, you can do it using the Export keyword.

Use export in the implementation file of the class. The members of the exported class are automatically declared as exported. (This is similar to a DLL)

The 20 template contains two names: independent of the templates parameters and those that depend on template parameters.
The designer's responsibility is to ensure that all names that do not depend on template parameters are defined in the scope of the template itself.
The responsibility of the template user is to ensure that the declarations of all functions, types, and operators associated with the type used to instantiate the template are visible. When instantiating a member or function template of a template, the user must ensure that the declarations are visible.

21 When you typically use the name of a class template, you must specify a template parameter. There is one exception to this rule: in the scope of the class itself, you can use the unqualified name of the class template.
The definition of a class template member function has the following form:
▲ must start with the keyword template, followed by the template parameter list of the class
▲ you must indicate which class it is a member of
▲ class names must contain their template parameters

22 class template member functions differ from other template functions: When instantiating a class template member function, the compiler does not perform the template argument inference, instead, the template parameter of the class template member function is determined by the type of the object that called the function. (This means that the arguments for the member function are already defined when the object is defined.) The member functions of the other class template are instantiated only for use by the program. If a function is never used, the member function is not instantiated.
Non-type template arguments must be compile-time-constant expressions.

23 There can be three kinds of friend declarations in the template class, each of which declares a friend relationship with one or more entities:
Generic non-template class or a friend declaration of a function that grants a friend relationship to a class or function that is explicitly specified
A friend declaration for a class template or function template that grants access to all instances of a friend
A friend declaration that only belongs to access to a specific instance of a class template or function template
Note that when you grant access to all instances of a given template, you do not need to have a declaration of that class template or function template in the scope. In fact, the compiler treats a friend declaration as a declaration of a class or function.
When you want to limit a friend relationship to a particular instantiation, you must declare a class or function before you can declare it with Yu Youyuan, which you can understand whether a class template or a function template must follow the usage rules of a variable: first defined and then used.

24 when you define a member template within the scope of a class template, you must include two template parameters: class template parameters and their own template parameters. (Note order)

Static members of the 25 class template: Used like a member function that is not a template, when defining a static member, the definition of the data member must appear outside the class.

The specificity of a function template is a definition in which the actual type or actual value of one or more template parameters is specified, in the form of the following:
Keyword template followed by a pair of empty angle brackets (<>);
Then the template name and a pair of angle brackets are specified, and the template parameters of this special definition are assigned in angle brackets;
function parameter list;
function body.
Example:
Special version of compare to handle c-sytle character strings

Template <>

int Compare<const char*> (const char*const& v1,const char* const&)

{

Return strcmp (V1,V2);

}

1 As with any function, function template specificity can be declared without definition. Template-specific declarations look like definitions, but ignore the body of the function.
When a template function is defined, a general conversion is applied to the argument. The conversion is not applied to the argument type when the template is customized. In a template-specific version invocation, the argument type must exactly match the formal parameter type of the special version function, and if it does not, the compiler instantiates an instance of the argument from the template definition.
As with other declarations, you should include a template-specific declaration in a header file, and then include the header file with each source file that you use for that special.
For the same template with the same template argument set, the program cannot have both explicit and instantiation.

2 class template customization should define the same interface as its special template, or it would be strange if the user tried to have that undefined member. When you define a member externally, the member cannot precede the template<> tag.
The definition of a partially-defined domain generic template does not conflict at all. Partial specificity can have a completely different set of members than a generic class template. The generic definition of a class template member is never used to instantiate a member of a class template that is partially specific.

3 function matching and function template
If the overloaded function has both a normal function and a function template, the steps to determine the call to the function are as follows:

Set up a set of candidate functions for this function name, including:

Any ordinary function with the same name as the called function

An arbitrary function template is instantiated, in which templates argument inference discovers template arguments that match the function arguments used in the call.

It is possible to determine those common functions. Each template instance in the candidate set is feasible because the template argument infers that the function can be invoked.

If you need to convert to make a call, arrange the feasible function according to the type of transformation, and remember that the conversion allowed by the instance calling the template function is limited.

Call this function if only one candidate function is optional

If the call has two semantics, remove all function template instances from the set of feasible functions

Rearrange possible functions to remove instances of function templates

Call this function if there is only one function to choose from

Otherwise it has ambiguity.

30 it is difficult to design an overloaded set of functions that includes both a function template and a non-template function, because it may be strange for the user of the function, and defining the function template is almost always better than using a non-template version.

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.