1 Definition:
function templates only apply to cases where the number of parameters is the same but the type is different and the function body is the same
2 This example does not use a template case
#include <iostream>using namespacestd;voidSwap (int&a,int&b) { intt =A; A=b; b=t;}voidSwap (Double&a,Double&b) { Doublet =A; A=b; b=t;}intmain1 () {//long a = 2; //long B = 3; //Swap (A, b); intA =2; intb =3; Swap (A, b);//but not a double. Introducing templates for general purposecout << a << b <<Endl; Cin.Get(); return 1;}
3 after using the template
1#include <iostream>2#include <string>3 using namespacestd;4 5 /*6 function templates apply only to the same number of parameters but differ in type and function7 in the same situation, otherwise it may not8 */9Template <typename t>//Here typename can be changed to classTen voidSwap (t &a, T &b) One { AT t =A; -A =b; -b =T; the } - - intmain2 () - { + intA =Ten; - intb = -; + Swap (A, b); Acout << a << b <<Endl; at - Longc =Ten; - LongD = -; - Swap (c, D); -cout << C << D <<Endl; - in stringSA ="Hello"; - stringSB ="Zzong"; to Swap (SA, SB); +cout << sa << SB <<Endl; - theCin.Get(); * return 1; $}
----------------------->
C + + function templates 1