A brief analysis of the template in C + + _c language

Source: Internet
Author: User
Tags int size

1. What is a template

Let's say we're done with a function of two numbers x and y to find the x^2 + y^2 + x * Y. Given that x and y may be int, float, or double, then we're going to complete three functions:

int fun (int x,int y);
Float Fun (float x,float y);
Double Fun (double x,double y);

and the operations within each fun function are extremely similar. As follows:

Copy Code code as follows:

int fun (int x,int y)
{
int tmp = x *x + y * y + x * y;
return TMP;
}
Float Fun (float x,float y)
{
float TMP = x *x + y * y + x * y;
return TMP;
}
Double Fun (double x,double y)
{
Double tmp = x *x + y * y + x * y;
return TMP;
}

It can be seen that the above three function bodies in addition to the different types, the other is exactly the same, so if you can write only one function can be completed above the function of the three functions how good? If you extract a common function from these three functions, and it applies to these three different types of data, this can greatly increase the reuse rate of your code. In fact, the template in C + + is just the right way to solve this problem. A template can implement a type of parameterization (defining a type as a parameter) to achieve true code reusability. The templates in C + + can be divided into function templates and class templates, and the materialization of function templates is called template functions, and the materialization of class templates becomes template classes. Let's take a look at what is function template and class template.

2. Template function

In fact, we use the function template, only need one function is possible to complete the above three functions, thousands of words to see the code:

Copy Code code as follows:

#include <iostream>

using namespace Std;

Template <typename t>
T Fun (t x,t y)
{
T tmp = x *x + y * y + x * y;
return TMP;
}
int main ()
{
int x1 = 1,y1 = 4;
Float x2 = 1.1, y2 = 2.2;
Double x3 = 2.0, y3 = 3.1;
Cout<<fun (x1,y1) <<endl;
Cout<<fun (x2,y2) <<endl;
Cout<<fun (X3,Y3) <<endl;
return 0;
}


Run Result:

So using the template, we are very easy to achieve our goal, and this greatly improve the reusability of the code, which also reminds us of those algorithms in the STL, these algorithms use a variety of data types. In fact the STL even the important application of the template.

Now we think what happens if the above code calls fun (X1,y2) like this? Click Compile to make this error:

You can see the problem with compiling compilation is fun (x1,y2), meaning that there is no corresponding function, either x1 and y2 are int, or both X1 and Y2 are float. So why should I say something like that? The main purpose is to draw out the template can also be used at the same time two:

Copy Code code as follows:

#include <iostream>

using namespace Std;


Template <typename T1, TypeName t2>
T2 Fun (T1 x,t2 y)
{
T2 tmp = x *x + y * y + x * y;
return TMP;
}
int main ()
{
int x1 = 1,y1 = 4;
Float x2 = 1.1, y2 = 2.2;
Double x3 = 2.0, y3 = 3.1;
Cout<<fun (x1,y1) <<endl;
Cout<<fun (x2,y2) <<endl;
Cout<<fun (X3,Y3) <<endl;
Cout<<fun (x1,y2) <<endl;
return 0;
}


Run Result:

Why is Fun (x1,y1) working correctly when using two templates? Because when this call is made, T1 = int, T2 = Int. So there is no problem with this call.

It is natural to think of overloading as a function, so can the template function be overloaded? Obviously can, or look at the code:

Copy Code code as follows:

#include <iostream>

using namespace Std;


Template <typename T1, TypeName t2>
T2 Fun (T1 x,t2 y)
{
cout<< "called the fun function of two parameters ^^" <<endl;
T2 tmp = x *x + y * y + x * y;
return TMP;
}
Template <typename t>
T Fun (t X, t y, T Z)
{
cout<< "called the fun function of three parameters ^^" <<endl;
T-TMP = x * x + y * y + z * z + x * y * z;
return TMP;
}
int main ()
{
int x1 = 1, y1 = 4, z1 = 5;
Float x2 = 1.1, y2 = 2.2;
Double x3 = 2.0, y3 = 3.1;
Cout<<fun (x1,y1) <<endl;
Cout<<fun (x2,y2) <<endl;
Cout<<fun (X3,Y3) <<endl;
Cout<<fun (x1,y2) <<endl;
Cout<<fun (X1,Y1,Z1) <<endl;
return 0;
}


Run Result:

It is clear from the result that there is no problem with the overload of the template function. Is it possible to overload between the template function and the non template function??

Copy Code code as follows:

#include <iostream>

using namespace Std;

Template <typename t>
T Fun (t x,t y)
{
cout<< "called the template function ^^" <<endl;
T tmp = x * x + y * y + x * y;
return TMP;
}
int fun (int x,int y)
{
cout<< "called Non-template function ^^" <<endl;
int TMP = x * x + y * y + x * y;
return TMP;
}

int main ()
{
int x1 = 1, y1 = 4;
Float x2 = 1.1, y2 = 2.2;
Cout<<fun (x1,y1) <<endl;
Cout<<fun (x2,y2) <<endl;
return 0;
}


Run Result:

Look to see that template functions and non-template functions can also be overloaded, so what is the order of the overloaded functions called? In fact, first look for the template function, to have a strictly matching template function, called the template function, can not find the appropriate non-template function in the template function and matching.

Here, tell me about the template.

3. Template class

If you understand the template function, the templates class is fairly simple, it's just that template functions use templates for types in functions, and template classes use templates for types in a class, which I'm not saying, the following code is a single linked list I used to write with templates, which is a typical application of templates: (tested)

Copy Code code as follows:

#include <stdio.h>
#include <iostream.h>

Template <class t>
struct Slnode
{
T data;
Slnode<t> *next;
Slnode (slnode<t> *nextnode=null)
{
Next = NextNode;
}
Slnode (const T &item,SLNode<T> *nextnode=null)
{
data = Item;
Next = NextNode;
}
};

Template <class t>
Class Sllist
{
Private
Slnode<t> *head;
Slnode<t> *tail;
Slnode<t> *currptr;
int size;
Public
Sllist ();
Sllist (const T &item);
~sllist ();
BOOL IsEmpty () const;
int Length () const;
BOOL Find (int k,t &item) const;
int Search (const T &item) const;
void Insertfromhead (const T &item);
void Insertfromtail (const T &item);
BOOL Deletefromhead (T &item);
BOOL Deletefromtail (T &item);
void Insert (int k,const T &item);
void Delete (int k,t &item);
void Showlistmember ();
};
Constructors
Template <class t>
Sllist<t>::sllist ()
{
Head = Tail = Currptr = new slnode<t> ();
size = 0;
}
Constructors
Template <class t>
Sllist<t>::sllist (const T &item)
{
tail = Currptr = new slnode<t> (item);
Head = new slnode<t> (CURRPTR);
size = 1;
}
destructor
Template <class t>
Sllist<t>::~sllist ()
{
Slnode<t> *temp;
while (! IsEmpty ())
{
temp = head->next;
Head->next = temp->next;
Delete temp;

}
}
Determine if the list is empty
Template <class t>
BOOL Sllist<t>::isempty () const
{
return head->next = = NULL;
}
Returns the length of a linked list
Template <class t>
int sllist<t>::length () const
{
return size;
}
Find thresholds for K-nodes
Template <class t>
BOOL Sllist<t>::find (int k,t &item) const
{
if (K < 1)
{
cout<< "Illegal position!" <<endl;
}
Slnode<t> *temp = head;
int count = 0;
while (temp!= NULL && count < K)
{
temp = temp->next;
count++;
}
if (temp = NULL)
{
cout<< "The list does not contain the K node!" <<endl;
return false;
}
item = temp->data;
return true;
}
Finding the data threshold for item is the first element of the table
Template <class t>
int Sllist<t>::search (const T &item) const
{
slnode<t> *temp = head->next;
int count = 1;
while (temp!= NULL && temp->data!= Item)
{
temp = temp->next;
count++;
}
if (temp = NULL)
{
cout<< "The node does not exist!" <<endl;
return-1;
}
Else
{
return count;
}
}
Insert from table header
Template <class t>
void Sllist<t>::insertfromhead (const T &item)
{
if (IsEmpty ())
{
Head->next = new slnode<t> (item,head->next);
Tail = head->next;
}
Else
{
Head->next = new slnode<t> (item,head->next);
}
size++;
}
Insert from end of table
Template <class t>
void Sllist<t>::insertfromtail (const T &item)
{
Tail->next = new slnode<t> (item,null);
Tail = tail->next;
size++;
}
Delete from table header
Template <class t>
BOOL Sllist<t>::D eletefromhead (T &item)
{
if (IsEmpty ())
{
cout<< "This is a empty list!" <<endl;
return false;
}
slnode<t> *temp = head->next;
Head->next = temp->next;
size--;
item = temp->data;
if (temp = = tail)
{
tail = head;
}
Delete temp;
return true;
}
Delete from end of table
Template <class t>
BOOL Sllist<t>::D eletefromtail (T &item)
{
if (IsEmpty ())
{
cout<< "This is a empty list!" <<endl;
return false;
}
Slnode<t> *temp = head;
while (Temp->next!= tail)
{
temp = temp->next;
}
item = tail->data;
tail = temp;
tail->next=null;
temp = temp->next;
Delete temp;
size--;
return true;
}
Inserts an item value after the K node
Template <class t>
void Sllist<t>::insert (int k,const T &item)
{
if (k < 0 | | | k > Size)
{
cout<< "Insert position illegal!" <<endl;
Return
}
if (k = = 0)
{
Insertfromhead (item);
Return
}
if (k = size)
{
Insertfromtail (item);
Return
}
slnode<t> *temp = head->next;
int count = 1;
while (Count < K)
{
count++;
temp = temp->next;
}
slnode<t> *p = temp->next;
Temp->next = new slnode<t> (item,p);
size++;
}
Delete the value of the K node and save it in item
Template <class t>
void Sllist<t>::D elete (int k,t &item)
{
if (k <= 0 | | | k > Size)
{
cout<< "Ileegal Delete position!" <<endl;
Return
}
if (k = = 1)
{
Deletefromhead (item);
Return
}
if (k = size)
{
Deletefromtail (item);
Return
}
slnode<t> *temp = head->next;
int count = 1;
while (Count < k-1)
{
count++;
temp = temp->next;
}
slnode<t> *p = temp->next;
Temp->next = p->next;
P->next = NULL;
item = p->data;
Delete p;
size--;
}
Template <class t>
void Sllist<t>::showlistmember ()
{
cout<< "List member:";
slnode<t> *temp = head->next;
while (temp!= NULL)
{
cout<<temp->data<< "";
temp = temp->next;
}
cout<<endl;
}

/*
1. The introduction of Insertfronhead,insertfromtail,deletefromhead and Deletefromtail to implement the insert and delete functions is a better approach.

2.SLNode (T &item,SLNode<T> *nextnode) This constructor is cleverly designed to facilitate the implementation of other member functions.

3. Inserts, deletes divides into: The table head, the footer, the middle inserts (deletes) three kinds of situations
*/

int main ()
{
int item;
Sllist<int> list (12);

List. Insert (0,11);
cout<< "List number:" <<list. Length () <<endl;
List. Showlistmember ();

List. Insert (2,14);
cout<< "List number:" <<list. Length () <<endl;
List. Showlistmember ();

List. Insert (2,13);
cout<< "List number:" <<list. Length () <<endl;
List. Showlistmember ();

List. Delete (2,item);
cout<< "item =" <<item<<endl;
cout<< "List number:" <<list. Length () <<endl;
List. Showlistmember ();

List. Delete (1,item);
cout<< "item =" <<item<<endl;
cout<< "List number:" <<list. Length () <<endl;
List. Showlistmember ();

List. Delete (2,item);
cout<< "item =" <<item<<endl;
cout<< "List number:" <<list. Length () <<endl;
List. Showlistmember ();
return 0;
}


The advantage of using a template is that the data in Sllist can be any type of data, which is the concept of generic programming.

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.