概述
模板可以幫助我們提高代碼的可用性, 可以幫助我們減少開發的代碼量和工作量.
函數模板
函數模板 (Function Template) 是一個對函數功能框架的描述. 在具體執行時, 我們可以根據傳遞的實際參數決定其功能. 例如:
int max(int a, int b, int c){ a = a > b ? a:b; a = a > c ? a:c; return a; } long max(long a, long b, long c){ a = a > b ? a:b; a = a > c ? a:c; return a; } double max(double a, double b, double c){ a = a > b ? a:b; a = a > c ? a:c; return a; }
寫成函數模板的形式:
template<typename T> T max(T a, T b, T c){ a = a > b ? a:b; a = a > c ? a:c; return a; }
類模板
類模板 (Class Template) 是創建泛型類或函數的藍圖或公式.
#ifndef PROJECT2_COMPARE_H #define PROJECT2_COMPARE_H template <class numtype> // 虛擬類型名為numtype class Compare { private: numtype x, y; public: Compare(numtype a, numtype b){x=a; y=b;} numtype max() {return (x>y)?x:y;}; numtype min() {return (x < y)?x:y;}; };
mian:
int main() { Compare<int> compare1(3,7); cout << compare1.max() << ", " << compare1.min() << endl; Compare<double> compare2(2.88, 1.88); cout << compare2.max() << ", " << compare2.min() << endl; Compare<char> compare3('a', 'A'); cout << compare3.max() << ", " << compare3.min() << endl; return 0; }
輸出結果:
7, 3
2.88, 1.88
a, A
模板類外定義成員函數
如果我們需要在模板類外定義成員函數, 我們需要在每個函數都使用類模板. 格式:
template<class 虛擬類型參數> 函數類型 類模板名<虛擬類型參數>::成員函數名(函數形參表列) {}
類模板:
#ifndef PROJECT2_COMPARE_H #define PROJECT2_COMPARE_H template <class numtype> // 虛擬類型名為numtype class Compare { private: numtype x, y; public: Compare(numtype a, numtype b); numtype max(); numtype min(); }; template<class numtype> Compare<numtype>::Compare(numtype a,numtype b) { x=a; y=b; } template<class numtype> numtype Compare<numtype>::max( ) { return (x>y)?x:y; } template<class numtype> numtype Compare<numtype>::min( ) { return (x>y)?x:y; } #endif //PROJECT2_COMPARE_H
類庫模板
類庫模板 (Standard Template Library). 例如:
#include <vector> #include <iostream> using namespace std; int main() { int i = 0; vector<int> v; for (int i = 0; i < 10; ++i) { v.push_back(i); // 把元素一個一個存入到vector中 } for (int j = 0; j < v.size(); ++j) { cout << v[j] << " "; // 把每個元素顯示出來 } return 0; }
輸出結果:
0 1 2 3 4 5 6 7 8 9
抽象和實例
到此這篇關于C++中模板(Template)詳解及其作用介紹的文章就介紹到這了,更多相關C++模板內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_46274168/article/details/116504709?spm=1001.2014.3001.5501