C++中模板(Template)詳解及其作用介紹
概述
模板可以幫助我們提高代碼的可用性, 可以幫助我們減少開發(fā)的代碼量和工作量.

函數(shù)模板
函數(shù)模板 (Function Template) 是一個(gè)對函數(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
類庫模板
類庫模板 (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è)元素顯示出來
}
return 0;
}
輸出結(jié)果:
0 1 2 3 4 5 6 7 8 9
抽象和實(shí)例

到此這篇關(guān)于C++中模板(Template)詳解及其作用介紹的文章就介紹到這了,更多相關(guān)C++模板內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
QT調(diào)用vs2019生成的c++動態(tài)庫的方法實(shí)現(xiàn)
本文主要介紹了QT調(diào)用vs2019生成的c++動態(tài)庫的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06
C語言結(jié)構(gòu)及隊(duì)列實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了C語言實(shí)現(xiàn)隊(duì)列示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
C/C++?Qt?Dialog?對話框組件應(yīng)用技巧
這篇文章主要介紹了C/C++?Qt?Dialog?對話框組件應(yīng)用,這里我將總結(jié)本人在開發(fā)過程中常用到的標(biāo)準(zhǔn)對話框的使用技巧,對C++?對話框組件相關(guān)知識感興趣的朋友一起看看吧2021-11-11

