?见代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | #include <iostream>#include <vector>using namespace std;template<typename T>T max(T a,T b,T c){ cout<<"primary template"<<endl; if(b>a) { a=b; } if(c>a) { a=c; } return a;}//形参个数不同的重载template<typename T>T max(T a, T b, T c, T d){ cout<<"override"<<endl; if(b>a) { a=b; } if(c>a) { a=c; } return a;}//特化T max(T a,T b,T c)#if 0 //oktemplate<>int max<int>(int a, int b, int c)#else//ok: explicit template argument int deduced fromparameter typestemplate<>int max(int a, int b, int c)#endif{ cout<<"template specialization"<<endl; if(b>a) { a=b; } if(c>a) { a=c; } return a;}//仅演示全特化/偏特化template<typename T1>bool min_test(T1 a, T1 b){ cout<<"min_test: primary template"<<endl; return true;}#if 1template<>bool min_test<int>(int a, int b){ cout<<"min_test: full template specialization"<<endl; return true;}#endif//全特化:全部参数指定类型//偏特化:部分参数指定类型#if 0//error: function template partial specialization ‘min_test<T1, int>’ is not allowedtemplate<typename T1, typename T2>bool min_test<T1, int>(T1 a, int b){ cout<<"min_test: partial template specialization"<<endl; return true;}#endiftypedef struct myval_s { int val0; int val1;}myval_t;int main( ){ int i1=185, i2=-76, i3=567, i; double d1=56.87, d2=90.23, d3=-3214.78,d; long g1=67854, g2=-912456, g3=673456, g; i=max(i1,i2,i3); cout<<"i_max="<<i<<endl<<endl; d=max(d1,d2,d3); cout<<"f_max="<<d<<endl<<endl; g=max(g1,g2,g3); cout<<"g_max="<<g<<endl<<endl; g=max(g1,g2,g3,g3); cout<<"g_max="<<g<<endl<<endl; min_test(i1, i2); min_test(d1, d2); return 0;} |
原文:http://www.cnblogs.com/freezlz/p/5324257.html