1. 程式人生 > >C++模板的使用

C++模板的使用

std push_back out algo names line emp ++ 定義

  1 #include <iostream>
  2 #include <algorithm>
  3 #include <bitset>
  4 #include <deque>
  5 #include <vector>
  6 
  7 // 用法1
  8 using std::cout;
  9 using std::cin;
 10 
 11 // 用法2 (最常用)
 12 using namespace std;
 13 
 14 void test1()
 15 {
 16     cout << ? << std::endl; //
std::endl 用法3 (直接 命名空間::(域)標識) 17 cout << @ << \n; 18 } 19 20 // 函數模板示範1 21 //template<typename T=int> // 只允許在類模板上文使用默認模板參數 22 template<typename T> 23 /*int*/T max(T a,T b) 24 { 25 return a>b ? a : b; 26 } 27 28 // 函數模板示範2 29 template<typename T> 30
bool equivalent(const T& a, const T& b){ 31 return !(a < b) && !(b < a); 32 } 33 34 // 類模板 35 template<typename T=int> // 默認參數,只允許在類模板上文使用默認模板參數 36 class bignumber{ 37 T _v; 38 public: 39 bignumber(T a) : _v(a) { } 40 inline bool operator<(const bignumber& b) const
; // 等價於 (const bignumber<T> b) 41 }; 42 43 // 在類模板外實現成員函數 44 template<typename T> 45 bool bignumber<T>::operator<(const bignumber& b) const 46 { 47 return _v < b._v; 48 } 49 50 // 常規函數一次只能處理一種數據類型 51 void swap(int&a , int& b) { 52 int temp = a; 53 a = b; 54 b = temp; 55 } 56 57 // 用使用template關鍵字聲明 類型名為 T (可變類型) 58 template<typename T> void swap(T& t1, T& t2); // 聲明 59 template<typename T> void swap(T& t1, T& t2) { // 定義(實現) 60 T tmpT; // 聲明 T 類型變量 tmpT; 61 tmpT = t1; // 將t1值賦給tmpT 62 t1 = t2; 63 t2 = tmpT; 64 } 65 66 void test2() 67 { 68 vector<int>vi; 69 int a; 70 while(true) 71 { 72 cout<<"輸入一個整數,按0停止輸入:"; 73 cin>>a; 74 if(a==0) break; 75 vi.push_back(a); 76 vector<int>::iterator iter; 77 for(iter=vi.begin();iter!=vi.end();++iter) 78 cout<<*iter; 79 } 80 } 81 82 int main(void) 83 { 84 test1(); 85 test2(); 86 87 // 模板函數可以自動識別 數據類型,所以不必重新編寫幾個函數代碼,一個模板就能實現 88 int x=1982,y=1983; 89 cout<<"max is " <<::max(x,y) << std::endl; 90 float f1=3.1416f, f2=3.15F; 91 cout<<"Max is " <</*(float)*/::max(f1,f2) << std::endl; 92 double d1=6.18e10; 93 double d2=6.18e11; 94 cout<<"Max is " <</*(double)*/::max(d1,d2) << std::endl; 95 96 bignumber<> a(1), b(1); // 使用默認參數,"<>"不能省略 97 std::cout << equivalent(a, b) << \n; // 函數模板參數自動推導 98 std::cout << equivalent<double>(1, 2) << \n; 99 100 //模板方法 101 int num1 = 199, num2 = 276; 102 cout << "numA: " << num1 << "\tnumB: " << num2 << endl; 103 ::swap<int>(num1, num2); 104 cout << "Swap: numA: " << num1 << "\tnumB: " << num2 << endl; 105 106 float numA = 3.1416f, numB = 6.18f; 107 cout << "\t\tnumA: " << numA << "\tnumB: " << numB << endl; 108 ::swap<float>(numA, numB); 109 cout << "\t\tSwap: numA: " << numA << "\tnumB: " << numB << endl; 110 111 std::cin.get(); // getchar(); cin>>x; 112 return 0; 113 }

C++模板的使用