C++ 程式中的模板特化?


在本教程中,我們將討論一個程式,以瞭解 C++ 中的模板特化。

像 sort() 這樣的標準函式可以用於任何資料型別,並且它們對每個資料型別的行為是相同的。但是,如果你想為特定資料型別(甚至是使用者定義的)設定函式的特殊行為,我們可以使用模板特化。

示例

 現場演示

#include <iostream>
using namespace std;
template <class T>
void fun(T a) {
   cout << "The main template fun(): " << a << endl;
}
template<>
void fun(int a) {
   cout << "Specialized Template for int type: " << a << endl;
}
int main(){
   fun<char>('a');
   fun<int>(10);
   fun<float>(10.14);
   return 0;
}

輸出

The main template fun(): a
Specialized Template for int type: 10
The main template fun(): 10.14

更新時間: 2020 年 3 月 2 日

144 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告