C ++ - function template

C ++ provides a function template provides a comparison function implementation of different data types, so that when comparing different types of data types, do not like the c language to write a function as an int, long int type to write a function ...... You will find that these functions are the same, except that the data type is not the same, so when we write the code would be very boring, and repetitive-create the wheel, does not make sense, if replaced with a global look, and if the variable name contains Some errors such as int occurs. Ever since the concept of function templates provided in c ++ inside.

Look at the type

template <typename T>
T Swap(T a[],T b[],int n);
template <typename T>
T Swap(T a[],T b[],int n)
{
	T t;
	for (int i=0; i<n; i++)
	{
		t=a[i];
		a[i]=b[i];
		b[i]=t;
	}
}

 The code is easy to implement a two code elements of the array are exchanged by the function template.

First of all

Use c ++ function template need to add a keyword template

Format template <typename / class T> where T represents the data type can be used in place of any non-keyword.

Then the function declarations, and other functions here is not the same type of data to use T instead.

Format is T + (function name) + (parameter a, parameter b) // there may continue to add more parameter

Then you can write the function like any other function achieved.

If you want to declare and implement a separate case, where the need to add the statement

template <typename /class T>

T + function name (parameter a, parameter b)

Local implementation should also add template <typename / class T>

 

To indicate that this is a template function. Then you can use
In function of the template source code as an example, two function is to achieve an element of the array interchanged.
#include <iostream>
using namespace std;
template <typename T>
T Swap(T a[],T b[],int n);
int main()
{
	int a[3]= {1,2,3},b[3]= {4,5,6};
	int i,n=3;
	for(i=0; i<n-1; i++)
		cout<<"a["<<i<<"]="<<a[i]<<" ";
	cout<<"a["<<i<<"]="<<a[i]<<" \n";
	for(i=0; i<n-1; i++)
		cout<<"b["<<i<<"]="<<b[i]<<" ";
	cout<<"b["<<i<<"]="<<b[i]<<" \n";
	Swap(a,b,n);
	for(i=0; i<n-1; i++)
		cout<<"a["<<i<<"]="<<a[i]<<" ";
	cout<<"a["<<i<<"]="<<a[i]<<" \n";
	for(i=0; i<n-1; i++)
		cout<<"b["<<i<<"]="<<b[i]<<" ";
	cout<<"b["<<i<<"]="<<b[i]<<" \n";
}
template <typename T>
T Swap(T a[],T b[],int n)
{
	T t;
	for (int i=0; i<n; i++)
	{
		t=a[i];
		a[i]=b[i];
		b[i]=t;
	}
}

 

 

Guess you like

Origin blog.csdn.net/CSDNsabo/article/details/91907763