(41.2) class template like the template application

Article Directory

1. Generic Programming

  • Process for the PO (procedure oriented), object-oriented OO (object oriented), generic programming GP (generic programming) are three programming reuse.

  • Early thoughts generic programming language C ++ only reflected in the simple template technology, the Standard Template Library STL (standard template library) after the actual embodiment and realization of generic programming ideas.

  • In a process-oriented function, to achieve the object code by the code segment through a function call encapsulated reuse.

  • Object-oriented object code, the object is achieved by a reusable class inheritance.

  • If you need to write a may be used for different data types of algorithm , the method may be employed are:
    ① a process-oriented approach: source code copied and modified to generate different data types versions of arithmetic functions, we need manual data type calling of Analyzing;
    ② object-oriented approach: in one class, the same name written in a plurality of functions, which have similar algorithms, but different types of data processing, of course, a function of parameters of different types, by overloading to automatically call (automatically call) version of the corresponding data type function.
    Obviously, the above two methods are required to write different function of many of the same algorithm, the code can not do true reuse. The main difference between both of them, just call convenient or not.
    If generic programming, you can realize reuse of the source code level.

  • The generic algorithms defined
    generic (generic) is a data fetch that allows different types of technologies, and the operation target data type independent algorithm is called generic algorithms, independent of any particular type of programming technique is called generic programming.

  • Template is the basis of generic programming.
    Generic programming focused on generating common software components, so that these components can be easily reused in different applications. In C ++, class templates and function templates are extremely effective mechanism for generic programming

  • Application eg class template

 #include <iostream>
using namespace std;
template <class T> //声明一个模板, 虚拟类型名为T
class Compare //类模板名为Compare
{
	public :
		Compare(T a,T b){x=a;y=b;}
		T max(){return (x>y)?x:y;}
		T min(){return (x<y)?x:y;}
	private :
		T x,y;
};
int main()
{
	Compare<int> a(4,7);//int对应T
	cout<<"a: max="<<a.max()<<",min="<<a.min()<<endl;
	return 0;
}
Published 556 original articles · won praise 140 · views 160 000 +

Guess you like

Origin blog.csdn.net/u011436427/article/details/104303553