Description of template functions and function template templates and templates

Source: Internet
Author: User
Tags float max

1. The concept of a template.
Reason for introducing the template:
We have learned how to reload functions. for heavy-duty functions, the C ++ checking mechanism can vary with function parameters and classes. Call the overload function correctly. For example, to obtain the maximum values of two numbers, we define the max () function to define different overloaded versions for different data types.
Int max (int x, int y );
{Return (x> Y )? X: Y;
}
Float max (float X, float y ){
Return (x> Y )? X: Y ;}
Double max (Double X, Double Y)
{Return (C> Y )? X: Y ;}
However, in the main function, we define char A and B respectively;
An error occurs when running max (a, B); because we have not defined an overloaded version of the char type.
Now, let's re-examine the above max () functions. They all have the same function, that is, to find the maximum value of two numbers. Can we write only one set of code to solve this problem? This will avoid calling errors caused by incomplete definition of overload functions. To solve the above problem, C ++ introduces a template mechanism. template definition: A template is a tool for implementing code reuse mechanisms. It can implement type parameterization, that is, define the type as a parameter, this achieves real code reusability. Template category: After the grinding board is divided into function templates, when the compilation system finds a corresponding function call, based on the type of the real parameter, determine whether to match the corresponding form parameter in the function template and generate an overload function, which is called the template function. The difference between a function template and a template function: the difference between the two can be analogous to the difference between a class and an object. Function templates and classes are similar to template definitions, while template functions are similar to objects. Is an instance of the function template with program code. Memory usage. After a class template is described, you can create an instance of the class template to generate a template class. The difference between a class template and a template class is that a class template is a template definition. Instead of a real class, a template class is a real class.
2. Events related to function templates and templates
The general life form of the function template is as follows:
Template <class type parameter table>
Return type function name (parameter table)
{// Function Definition body}
Note: templarte is a keyword of the Declaration template, indicating that the class of the Declaration template keyword cannot be omitted. If the type parameter is redundant, class <type parameter table> must be added before each parameter. It can contain basic data types and class types.
See the following program:
# Include <iostream. h>
Template <class T>/* function template declaration */
T min (t x, t y)
{If (x <Y) return X;
Else return y ;}
Void main ()
{Int n1 = 2, n2 = 10;
Double d1 = 1.5, D2 = 5.6;
Cout <"small integer:" <min (N1, N2) <Endl; // compares two integers in the instantiated min Template Function
Cout <"smaller real number:" <min (D1, D2) <Endl; // compare the two Double Precision values by instantiating the min Template Function
}
Program running result: small integer: 2
Smaller number: 1.2
Program analysis: the main () function defines two integer variables N1 and N2, D1 and D2, and then calls min (N1, N2 ); that is, the instantiation function template T min (t x, t y) where T is int type, find the minimum value in N1, N2. similarly, when min (D1, D2) is called, the minimum value in D1 and D2 is obtained.
It indicates the function template instantiation process.
Function template min (x, y)
Template Function min (N1, N2) int type
Template Function min (D1, D2) Double Type
If a cout <min (N1, D1) <Endl;
The program will encounter errors because the parameters of the template function T must be completely consistent with each other and do not have the implicit type conversion function.
Iii. Category templates and templates
1. Define a class template:
Template <class type parameter table>
Class class name {
// Class definition ......
};
Template declares the keywords of each template, indicating that a template can be declared. template parameters can be one or multiple, but they should be abstract results, it should not be a specific (such as Int or float) type, a member function parameter or a return type. The preceding parameter type must be added.
For example, define a class template:
Template <classt1, classt2>
Class myclass {T1 I ;//
T2 J ;//
Public:
Myclass (T1 A, T2 B )//
{I = A; j = B ;}
Void show ()
{Cout <"I =" <"J =" <j <Endl ;}};
If the main function defines a template class myclass <int, double> and declares a Class Object ob1 (1 Reference statement: myclass <int, double> OB (2, 0.1 ); note: myclass <int, double> instantiates the class template, that is, T1 instance is of the int type, T2 is of the double type, so we get a template class. then you can define the Class Object ob1 and initialize it.
You can also define another template class, such as myclass <double, char>.
Indicates the relationship between a class template and a template class.
Class template myclass <t !, T2>
Template Class myclass (INT, double)
Template Class nyclass <double, char>
Conclusion: A function template is a type of function abstraction that represents a type of function. This type of function has the same function and represents a specific function that can be called by class objects, function templates cannot be called by class objects.
A class template is an abstraction of a class that represents a class. These classes have the same functions, but the data member types and member function return types and parameter types are different. A template class is an instance of a template class. represents a specific class. class objects can be defined, but objects cannot be defined for class templates.
 

 

 

 

 

 

 

 

 

-------------------------------

Proper Name
There is an old saying in China that the name is not regular. If a name is not used well, it not only sounds uncomfortable, but also its true nature is easily concealed. If something has a good name, we can easily remember and understand it.

In modern Chinese, the focus of many words is behind, for example, the two words we often see below.

Ice and Snow smart.

Smart ice and snow.

Ice and Snow are smart, and she is as smart as ice and snow.

Smart ice and snow emphasizes the ice and snow. She is very smart and looks like ice and snow.

There are several such terms in C ++, but most of the time we use them is not correct, and they are almost replaced by each other. Below I want to thoroughly identify several terms, so as to avoid many conceptual obfuscation and usage errors.

These words are:

Function pointer -- pointer Function

Array Pointer -- pointer Array

Class template-template class

Function template-Template Function

In the end, we can make them actually named, and the name is justified.



1. function pointer -- pointer Function

Function pointers focus on pointers. A pointer pointing to a function. For example:

INT (* PF )();

Pointer functions focus on functions. Indicates a function, and its return value is a pointer. Example:

Int * Fun ();



2. array Pointer -- pointer Array

Array pointers focus on pointers. A pointer pointing to an array. For example:

INT (* pA) [8];

The focus of pointer arrays is arrays. Indicates an array, which contains a pointer. Example;

Int * AP [8];



3. class template-template class (class template-template class)

Class templates focus on templates. A template is used to generate a class model. Example:

Template <typename T>

Class Vector

{

...

};

This Vector Template can generate many classes, such as vector <int>, vector <char>, vector <int>, and vector <shape *> .......

The focus of the template class is the class. Indicates the class generated by a template. Example:

The preceding vector <int>, vector <char> ,...... All are template classes.

These two words are easy to confuse. I have seen many articles that use them incorrectly or even some English The same is true for the article. Separating them is very important, so you can understand why the header file of the template is defined. h, the template member function implementation must also be written in the header file. h, instead of writing the class declaration in. in the H file, the definition of Class is written in. CPP file. Refer to [34] container classes and templates in C ++ FAQ lite of Marshall Cline [34.12] Why can't I separate the definition of my templates class from It 'S declaration and put it inside a. cpp file? URL address is http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.12

I will extract several key paragraphs as follows, which are easy to understand in English:

In order for the compiler to generate the code, it must see both the template definition (not just Declaration) and the specific types/whatever used to "fill in" the template. for example, if you're trying to use a foo <int>, the compiler must see both the foo template and the fact that you're trying to make a specific Foo <int>.

Suppose you have a template Foo defined like this:

Template <class T>
Class Foo {
Public:
Foo ();
Void somemethod (t x );
PRIVATE:
T x;
};

Along with similar definitions for the member functions:

Template <class T>
Foo <t>: Foo ()
{
...
}

Template <class T>
Void Foo <t >:: somemethod (t x)
{
...
}

Now suppose you have some code in file bar. cpp that uses Foo <int>:

// Bar. cpp

Void blah_blah_blah ()
{
...
Foo <int> F;
F. somemethod (5 );
...
}

Clearly somebody somewhere is going to have to use the "pattern" for the constructor definition and for the somemethod () Definition and instantiate those when T is actually Int. but if you had put the definition of the constructor and somemethod () into file Foo. CPP, the compiler wocould see the template code when it compiled Foo. CPP and it wocould see Foo <int> when it compiled bar. CPP, But there wowould never be a time when it saw both the template code and foo <int>. so by rule above, it cocould never generate the code for foo <int >:: somemethod ().

Example of a default template parameter:

Template <typename T = int>

Class Array

{

...

};

This is the first time I defined this template and used it:

Array books; // I think there are default template parameters, which is equivalent to array <int> books

The above usage is incorrect and compilation fails because array is not a class. The correct usage is array <> books;

Here, array <> is a specific class generated by a class template used for default template parameters.



4. Function template-template function (function template-template function)

Function templates focus on templates. A template is used to produce functions. Example:

Template <typename T>

Void fun (t)

{

...

}

When using this function, you can explicitly produce template functions, such as fun <int>, Fun <double>, and fun <shape *> .......

You can also use the compiler to deduce template parameters during use to help you generate them implicitly (implicitly.

Fun (6); // implicitly generates Fun <int>

Fun (8.9); // implicitly generates Fun <double>

Fun ('A'); // implicitly generates Fun <char>

Shape * PS = new cirlcle;

Fun (PS); // implicitly generates Fun <shape *>



The focus of template functions is on functions. Indicates a function generated by a template. Example:

Fun <int> and Fun <shape *> generated by explicit or implicit (implicitly) above ...... All are template functions.

The template itself is a very huge topic. To make it clear, you need not an article, but a book. Fortunately, this book already has: David vanw.orde, nicola M. c ++ templates: the complete guide written by josutis. Unfortunately, the Chinese mainland cannot buy the paper version, but there is one Electronics The version has been circulating on the Internet.



The use of templates is very limited. Generally, they are just a model for generating classes and functions. In addition, there are very few fields used, so it is impossible to have any template pointer, that is, the pointer to the template, because in C ++, A template is a code production tool. In the final code, no template exists at all, and only the code of the specific classes and functions that the template has come up with exists.

However, a class template can also be used as a template parameter, policy-based design in Andrei Alexandrescu's modern c ++ design is widely used.

Template <typename T, template <typename u> class Y>

Class foo

{

...

};



From the discussion in the article, we can see that the name is very important. If you use the name improperly, it will cause a lot of trouble and misunderstanding. In actual programs, the naming of various identifiers is also a learning. In order to be clear and easy to understand, sometimes we still need to pay a certain price.

Note: In terms of this article, Language The center of gravity is behind, and the previous words are used as adjectives.

Wu Tong wrote in 2003.6.1

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.