I. Role of the template
It is a C ++ template support tool parametric polymorphism, usually with function templates and class templates
Function templates for different types of function parameters only
Template class data members and member functions for different types of class
Use a template to write and type-independent code
II. Function Template
1. Use
Template function, the template function which is replaced according to the type of incoming parameter argument
//声明 template <class T> void Swap(T&a ,T&b){ ... } template <typename T> void Swap(T& a,T& b){ }
// Call int A, b; Swap (A, b);
2. Examples
Note: a template declaration corresponds to a function
III. Class Templates
1. Use
Template class, depending on the particular type of Class <> template class which to replace the parameter type
//声明 template <class T> template <typename T> class A{ public: T a; T b; T swap(T c,T& d); }; //实现 T A<T>::swap(T c,T& d){ ... }
//调用 A<int> a; A<string> b;
2. Examples
Note: a template declaration corresponds to a class, and to override a different type
//TestMain.h template <class T> class A{ public: A(); T g(T a,T b); };
template <class T> A<T>::A(){ } template <class T> T A<T>::g(T a,T b){ return a+b; } int main(){ A<int> a; std::cout<<a.g(1,2)<<std::endl; system("pause"); return 0; }
IV. Generic programming principles