Detailed description of template usage in C ++-Excellent description

Source: Internet
Author: User
Tags float max

1. The concept of a template.

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. Writing function templates

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. Writing of class templates

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;

...

};

Article from:Http://www.360doc.com/content/09/0403/17/799_3011262.shtml

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.