Simple template concept

zhaozj2021-02-11  166

I used to have an understanding of the template, so I prepared a special study of the system. I thought it took a two-day time. I didn't expect it. I didn't think of it. I completed the plan, I took a look, the template is nothing more than just So? So, this topic is called "Simple Template Concept".

Those who throw out other relevant books and materials, I will describe the template in a simple language according to my own understanding.

(Of course, in fact the template has its own complicated side, huh, I don't discuss this)

Template role

Humph! Why is a function of a class that can only use a fixed data type? I am just the same type, but the processing is exactly the same, this code repetition rate has increased! Is there anything - wrong!

This is what I have an indignant, until I found the template, huh, huh, it is a good thing. It can increase the code reuse. It uses a non-specific type definition class or function to replace them with a specific type when used.

N, in order to reduce the code redundancy and text reuse, this is not exemplified, exemplified in the following two sections.

2. Class Template

Using templates in the definition of class is our most - common, you see, there is ATL, there is STL, huh, huh, a lot.

Guan - keyword (Zhou Xing Chiqi): Template

Key symbol: <>

It is the key to say that the two have two less, how can it be used? After reading this simple example, you will immediately:

#include

Template

Class myclass {

T Temp;

PUBLIC:

Myclass (t name) {

TEMP = Name;

}

T Vomit () {

Return Temp;

}

}

void main ()

{

Myclass T1 (2);

Cout << t1.vomit () << endl;

Myclass t2 ("drunken");

Cout << t2.vomit () << endl;

Myclass T3 (3.14159);

Cout << t3.vomit () << endl;

}

Don't tell me, you didn't understand, or do it, don't tell me how you don't do it! Pour ~~~ See no, before the normal class definition, add Template so that T is the type that can be used in this class. When used, the class name and T are used together to correctly represent this class, and use the determined type instead of this T, just like myclass , myclass written above. OK is as simple as it is.

Pay attention to the function VOMIT (Who can say its English meaning? Oh, here is the inline function, then put him in the outside of the class? How to define? Oh, just like this:

Template

T myclass :: vomit () {

Return Temp;

}

First, before adding the same template , the class name must be noted, and it is myclass instead of myclass. OK, class template knows this.

3. Function Template

Like the class template, the function can also use a lot of type to realize code reuse, give an example, don't say, you can see it, or run, I am very simple example, aiming to reveal the principle:

#include

Template

Void F (t qie)

{

Cout << qie << Endl;

}

#define x f

void main ()

{

F (3);

F ('r');

X ("AADF");

}

Run a look?

转载请注明原文地址:https://www.9cbs.com/read-5921.html

New Post(0)