C + + function templates allow you to define functions in any type of way. For example, you can create a swap template like this:
Template <typename anytype>void Swap (AnyType &a, AnyType &b) { AnyType temp; = A; = B; = temp;}
Before standard c++98 adds keyword typename, C + + uses the keyword class to create a template. In other words, you can write a template definition like this:
Template <class anytype>void Swap (AnyType &a, AnyType &b) { AnyType temp;< c13/>= A; = B; = temp;}
You can use a template when you need multiple functions that use the same algorithm for different types. However, not all types use the same algorithm, and in order to meet this requirement, it is possible to flush the definition of the template as if it were overloaded with regular function definitions. As with regular overloads, the function characteristics of the template being overloaded must be different.
A new interchange template is added to the following routines to exchange elements in two arrays.
#include <iostream>using namespacestd;template<typename t>voidSwap (t &a, T &b); template<typename t>voidSwap (t *a, T *b,intn);voidShow (inta[]);intMain () {intx =1, y =2; Swap (x, y); cout<< x <<"\ t"<< y <<Endl; inta[Ten], b[Ten], n =Ten; for(inti =0; I <Ten; i + +) A[i]= i +1, b[i] =Ten-i; Swap (A, B,Ten); Show (a); Show (b); return 0;} Template<typename t>voidSwap (t &a, T &b) {T temp=A; A=b; b=temp;} Template<typename t>voidSwap (t a[], T b[],intN) {T temp; for(inti =0; I < n; i + +) {Temp=A[i]; A[i]=B[i]; B[i]=temp; }}voidShow (inta[]) { for(inti =0; I <Ten; i + +) cout<< A[i] <<" "; cout<<Endl;}
Output effect:
2 1
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
Explicit materialization
Instance (actual run error, possibly Compiler version issue):
#include <iostream>using namespacestd;template<typename t>voidSwap (t &a, T &b);structjob{Charname[ +]; Doublesalary; intFloor ;};//Explicit SpecializationTemplate <>voidSwap<job> (Job &j1, &J2);voidShow (Job &j);intMain () {intA =1, B =2; Swap (A, b); cout<< a <<"\ t"<< b <<Endl; Job J1 {"Moon",3000.3,2}; Job J2 {"lit",2000.2,1}; Swap (J1, J2); Show (J1); Show (J2); return 0;} Template<typename t>voidSwap (t &a, T &b) {T temp=A; A=b; b=temp;} Template<>voidSwap<job> (Job &j1, Job &J2) { DoubleT1; T1=j1.salary; J1.salary=j2.salary; J2.salary=T1; intT2; T2=J1.floor; J1.floor=J2.floor; J2.floor=T2;}voidShow (Job &j) {cout<< J.name <<"\ t"<< j.salary <<"\ t"<< J.floor <<Endl;}
Tip:template <> void swap<job> (Job &j1, &j2); Error.
Instantiation and Materialization
。。。
C + + function templates