概述
模板可以幫助我們提高代碼的可用性, 可以幫助我們減少開(kāi)發(fā)的代碼量和工作量.
函數(shù)模板
函數(shù)模板 (Function Template) 是一個(gè)對(duì)函數(shù)功能框架的描述. 在具體執(zhí)行時(shí), 我們可以根據(jù)傳遞的實(shí)際參數(shù)決定其功能. 例如:
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; }
寫成函數(shù)模板的形式:
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) 是創(chuàng)建泛型類或函數(shù)的藍(lán)圖或公式.
#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; }
輸出結(jié)果:
7, 3
2.88, 1.88
a, A
模板類外定義成員函數(shù)
如果我們需要在模板類外定義成員函數(shù), 我們需要在每個(gè)函數(shù)都使用類模板. 格式:
template<class 虛擬類型參數(shù)> 函數(shù)類型 類模板名<虛擬類型參數(shù)>::成員函數(shù)名(函數(shù)形參表列) {}
類模板:
#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
類庫(kù)模板
類庫(kù)模板 (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); // 把元素一個(gè)一個(gè)存入到vector中 } for (int j = 0; j < v.size(); ++j) { cout << v[j] << " "; // 把每個(gè)元素顯示出來(lái) } return 0; }
輸出結(jié)果:
0 1 2 3 4 5 6 7 8 9
抽象和實(shí)例
到此這篇關(guān)于C++中模板(Template)詳解及其作用介紹的文章就介紹到這了,更多相關(guān)C++模板內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_46274168/article/details/116504709?spm=1001.2014.3001.5501