Template template based learning

Template template

Template concept

1 is a so-called template-free type parameters to generate a series of mechanisms function or class.
2. If the program is a function for a particular type of data processing, the data can be described as a type of processing parameters to be used in the case of other types of data, which is the origin of the template.
3. The template is a completely general approach to the design function or class without previously described type of each object to be used.
4 may be generated by a class or function set of templates, so that different types of data they operate, thereby avoiding the need to generate a separate function for each class or type of data
required to achieve a large value template function
Example:
1. the sum of two numbers a large value, using the template
template <class T>
T max (Ta, T B)
{
? return (A> B) A: B;
}
2.template <template parameter list> <return type>
<function name> ( template function parameter list)
{} // function definition body

#include<iostream>
using namespace std;
template <class T>     
T min(T a,T b)
{
	return (a>b) ? a:b;
}
int main(int argc, char* argv[])
{

	cout<<min(1,2)<<" "<<min('a','b')<<" "<<min(5.3,2.2)<<endl;
	return 0;

Here Insert Picture Description

#include <iostream>
using namespace std;
template <class T>
T min(T a[],int n)
{
	int i;
	T minv=a[0];
	for( i = 1;i < n ; i++){
		if(minv>a[i])
		minv=a[i];
	}
	return minv;
}


int main(int argc, char *argv[])
{
    int a[]={1,3,0,2,7,6,4,5,2};
    double b[]={1.2,-3.4,6.8,9,8};
    cout<<"a数组的最小值为:"<<min(a,9)<<endl;
    cout<<"b数组的最小值为:"<<min(b,4)<<endl;   
    system("PAUSE");	
    return 0;
}

Here Insert Picture Description

Template works

Function template simply stated, can not be executed directly, you need to perform after instance into a template function;
in the description of a function template later, when compiling the system has found a corresponding function call to confirm whether the match will be based on the argument of type corresponding to the template function parameter, and generates a reload function. The same function definition body member and defines the function template overloaded functions, it is called template function

The advantages and disadvantages of the template

It represents a function template method overcomes the C language solve the problem with a lot of different function names similar function of bad habits; to overcome the macro definition can not be parameterized type checking drawbacks; to overcome the C ++ function overloading with the same function name rewrite several functions cumbersome.
Shortcomings, debugging more difficult.  usually the first to write a special version of the function; after  run correctly, change the template function

Guess you like

Origin blog.csdn.net/qq_41767945/article/details/90271380