Introduction to C + + template (template) usage

Source: Internet
Author: User
Tags class definition float max function definition

1. The concept of the template.

We've learned about overloading (overloading), and for overloaded functions, C + + inspection mechanisms can vary by function parameters and the classes they belong to. The correct call to the overloaded function. For example, to find the maximum of two digits, we define the max () function to define different overloaded (overload) versions of different data types.

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;}

But if in the main function, we define char a,b separately; Then in the execution Max (A,B), the program will go wrong because we do not have an overloaded version of the char type defined.

Now, let's revisit the Max () function, which has the same function of asking for a maximum of two digits, and can only write a single set of code to solve the problem. This avoids calling errors caused by incomplete overload function definitions. To solve the above problems C + + introduce template mechanism, template definition: template is to implement code reuse mechanism of a tool, it can implement type parameterization, that is, the type defined as parameters, so as to achieve real code reusability. Templates can be divided into two categories, one is the function template, the other is a class template.

2. The writing function template

The general form of a function template is as follows:

Template <class or you can also use typename t>

return type function name (formal parameter list)
{//function definition Body}

Description: Template is a keyword to declare a template, which means that declaring a template keyword class cannot be omitted, and if the type parameter is redundant, each formal parameter must be added with class < type parameter table > can contain the base data type that can contain the class type.

Please see the following program:

//test.cpp

#include <iostream>

Using Std::cout;

Using Std::endl;

Declares a function template that compares the size of two parameters of the same data type entered, and class can 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<< "Smaller real number:" <<min (D1,D2) <<endl;

System ("PAUSE");

}

Program Run Result:

Program Analysis: the main () function defines two integer variable n1, n2 two double-precision type variable d1, d2 then calls Min (N1, N2), that is, the instantiation function template T min (t x, t y) where T is int, find the minimum value in the N1,N2. When you call min (D1,D2) in the same vein, you find the minimum value in D1,D2.

3. The writing of class template

Define a class Template:

Template < class or you can also use typename T >
Class Name {
Class definition ...
};

Description: In which, template is the keyword that declares each template, declares a template, the template parameter can be one, or can be multiple.

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 results show:

4. Non-typed template parameters

In general, non-type template parameters can be constant integers (including enumerations) or pointers to external linked objects.

So that means the floating-point number is not, and pointing to the internal linked object is not possible.

Template<typename T,int maxsize>

Class stack{

Private:

T Elems[maxsize];

...

};

Int Main ()

{

Stack<int, 20> Int20stack;

Stack<int, 40> Int40stack;

...

};


About C++template Understanding:
C++template contains two of function templates and class templates, as the name suggests the difference between the two is the use of different occasions, function templates for functions, and class templates for class use.
What's the advantage of using a class template? Now you want to write a maximum number of methods, you take into account the N case (two integers, find two floating-point numbers, two characters, please ...) Then you might write n overloaded methods, when you're racking your brains to think of everything that can happen. This program is finished, the amount of code is a lot of, this time to solve this problem is a good way is to use C + + template, we can define a function template, this template to receive any type of parameters, The compiler compiles the corresponding type of function according to the type of parameter you pass in, and the return value of the corresponding type. The
template, in my understanding, is to define a public requirement, for example, the template for this Word document defines the styles that everyone might use, and the C + + template lets you define a common module that classifies modules of similar functionality into a template, and what is the benefit of using a template. I think I can improve the reusability of the program, reduce the redundancy of the Code and the amount of code.

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.