C ++ template Learning

Source: Internet
Author: User
Tags float max

1.Template concept.

We have learnedOverloading)For overloaded functions, the C ++ check mechanism can be implemented through different function parameters and different classes. Call the overload function correctly. For example, to obtain the maximum values of two numbers, we define the max () function to define different data types.Overload)Version.

// Function 1.

Int max (int x, int y );
{Return (x> Y )? X: Y ;}

// Function 2.
Float max (float X, float y ){
Return (x> Y )? X: Y ;}

// Function 3.
Double max (Double X, Double Y)
{Return (C> Y )? X: Y ;}

However, if char A and B are defined in the main function, an error occurs when Max (A, B) is executed, because we do not define the 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 these problems, C ++ introduces a template mechanism,Template definition: A template is a tool for implementing the code reuse mechanism. It can implement type parameterization, that is, define the type as a parameter, thus realizing real code reusability. Templates can be divided into two types: function templates and class templates.

2.Function template writing

The function template is generally in the following format:

Template <ClassOr you can useTypenameT>

Return type function name (parameter table)
{// Function Definition body}

Description: Template is a keyword used to declare a template. It indicates that the class that declares a 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:

// Test. cpp

# Include <iostream>

Using STD: cout;

Using STD: Endl;

// Declare a function template to compare the input values of two parameters of the same data type. The class can also be replaced by typename,

// T can be replaced by any letter or number.

Template <class T>

T min (t x, t y)

{Return (x <Y )? X: Y ;}

Void main ()

{

Int n1 = 2, n2 = 10;

Double d1 = 1.5, D2 = 5.6;

Cout <"small integer:" <min (N1, N2) <Endl;

Cout <"small real number:" <min (D1, D2) <Endl;

System ("pause ");

}

Program running result:

 

 

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.

3.Class template writing

Define a class template:

Template <ClassOr you can useTypenameT>
Class class name {
// Class definition ......
};

Note: "template" declares the keywords of each template, indicating that a template can be declared. The template parameter can be either a template or multiple templates.

For example, define a class template:

// Classtemplate. h
# Ifndef classtemplate_hh

# Define classtemplate_hh

Template <typename T1, typename T2>

Class myclass {

PRIVATE:

T1 I;

T2 J;

Public:

Myclass (T1 A, T2 B); // Constructor

Void show ();

};

// This is the constructor.

// Note these formats

Template <typename T1, typename T2>

Myclass <T1, T2 >:: myclass (T1 A, T2 B): I (a), J (B ){}

// This is void show ();

Template <typename T1, typename T2>

Void myclass <T1, T2 >:: show ()

{

Cout <"I =" <I <", j =" <j <Endl;

}

# Endif

// Test. cpp

# Include <iostream>

# Include "classtemplate. H"

Using STD: cout;

Using STD: Endl;

Void main ()

{

Myclass <int, int> class1 (3, 5 );

Class1.show ();

Myclass <int, char> class2 (3, 'A ');

Class2.show ();

Myclass <double, int> class3 (2.9, 10 );

Class3.show ();

System ("pause ");

}

The final result shows:

 

4. Non-type template parameters

Generally, a non-type template parameter can be a constant INTEGER (including enumeration) or a pointer to an external linked object.

That is to say, floating point numbers cannot be used, and pointers to internal linked objects cannot be used.

Template <typename T, int maxsize>

Class Stack {

PRIVATE:

T elems [maxsize];

...

};

Int main ()

{

Stack <int, 20> int20stack;

Stack <int, 40> int40stack;

...

};

5. Use the template type

Sometimes the template type is a container or class. To use the type under this type, you can call it directly. The following is a template function that can print the sequence and chain of containers in STL.

Template <typename T>
Void print (t v)
{
T: iterator itor;
For (itor = V. Begin (); itor! = V. End (); ++ itor)
{
Cout <* itor <"";
}
Cout <Endl;
}

Void main (INT argc, char ** argv ){
List <int> L;
L. push_back (1 );
L. push_front (2 );
If (! L. Empty ())
Print (L );
Vector <int> VEC;
VEC. push_back (1 );
VEC. push_back (6 );
If (! VEC. Empty ())
Print (VEC );
}

Print results

Implicit type conversion for Type Derivation
Before determining the template parameter type, the compiler performs the following implicit type conversion:

Left value transformation
Modifier Conversion
Conversion from a derived class to a base class

See C ++ primer ([NOTE 2], P500.

In short, the compiler weakens some type attributes, such as the left Value Attribute of the reference type in our example. For example, the compiler instantiates a function template with a value type instead of a reference type.

Similarly, it uses the pointer type to instantiate the function template, rather than the corresponding array type.

It removes the const modifier and never uses the const type to instantiate the function template. It always uses the corresponding non-const type, but for pointers, the pointer and const pointer are different types.

Bottom line: Automatic template parameter derivation includes type conversion, and some type attributes will be lost when the compiler determines the template parameters automatically. These types of attributes can be retained when explicit function template parameter declarations are used.

6. Special Template
If we want to write a function for a specific type of template function (class), we need to use the template features. For example, when we plan to use the long type to call Max, return a small value (Forgive me for giving an inappropriate example ):
Template <> // This indicates that the following is a template function.
Long max <long> (long a, long B) // for VC, <long> can be omitted here.
{
Return A> B? B:;
}
In fact, the so-called special mode is to replace the compiler to complete the special work for the specified type. This technique is widely used in modern template libraries.
For bitwise, only some types in the template type are specified, as shown in figure

Template <T1, T2>

Class myclass;

Template <T1, T2>

Class mycalss <int, T2> // bitwise
7. Function imitation
The word imitation function is often used in the template library (such as STL). So what is imitation function?
As the name implies: a function is something that can work like a function. Forgive me for using something as a pronoun. I will explain it slowly below.
Void dosome (int I)
This dosome is a function. We can use it like this: dosome (5 );
So, is there anything that can work like this?
Answer 1: the object of the () operator is overloaded. Therefore, two points need to be clarified here:
1. A function is a class instead of a function;
2. the imitation function reloads the () operator so that it can be called like a function (the code is like calling:
Struct dosome
{
Void operator () (int I );
}
Dosome;
Here the class (for C ++, struct and class are the same) overload the () operator, so its instance dosome can use dosome (5) like this ); it is exactly the same as the above function call, isn't it? So dosome is an imitation function.

In fact, there is still answer 2:
The object to which the function pointer points.
Typedef void (* dosomeptr) (INT );
Typedef void (dosome) (INT );
Dosomeptr * PTR = & func;
Dosome & dosome = * PTR;

Dosome (5); // This is exactly the same as the function call.
Of course, Answer 3: The member function pointed to by the member function pointer is the expected answer.

8. Use of function imitation
Objects, function pointers, and so on can be passed as parameters or saved as variables. Therefore, we can pass a function to a function that calls this function as needed (similar to callback ).
This technique is widely used in the STL template library to achieve "flexibility" of the library ".
For example:
For_each, whose source code is roughly as follows:
Template <typename iterator, typename functor>
Void for_each (iterator begin, iterator end, fucntor func)
{
For (; begin! = End; begin ++)
Func (* begin );
}

This for loop traverses every element in the container and calls the func function for each element, so that the idea of doing the same thing for each element is realized.

In particular, if a function imitation is an object, this object can have member variables, which gives the function a "state" and achieves higher flexibility.

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.