C++ 中的模板特化


在 C++ 中,模板用於建立泛型函式和類。因此,我們可以使用任何型別的資料,例如 int、char、float,或一些使用者定義的資料以及使用模板。

在本節中,我們將瞭解如何使用模板特化。現在,我們可以為不同型別的資料定義一些泛型模板。對於特殊型別的資料,還可以使用一些特殊模板函式。讓我們看一些示例來更好地理解。

示例程式碼

#include<iostream>
using namespace std;
template<typename T>
void my_function(T x) {
   cout << "This is generalized template: The given value is: " << x << endl;
}
template<>
void my_function(char x) {
   cout << "This is specialized template (Only for characters): The given value is: " << x << endl;
}
main() {
   my_function(10);
   my_function(25.36);
   my_function('F');
   my_function("Hello");
}

輸出

This is generalized template: The given value is: 10
This is generalized template: The given value is: 25.36
This is specialized template (Only for characters): The given value is: F
This is generalized template: The given value is: Hello

模板特化也可以為類建立。讓我們透過建立泛型類和特化類來看一個示例。

示例程式碼

#include<iostream>
using namespace std;
template<typename T>
class MyClass {
   public:
      MyClass() {
         cout << "This is constructor of generalized class " << endl;
      }
};
template<>
class MyClass <char>{
   public:
      MyClass() {
         cout << "This is constructor of specialized class (Only for characters)" << endl;
      }
};
main() {
   MyClass<int> ob_int;
   MyClass<float> ob_float;
   MyClass<char> ob_char;
   MyClass<string> ob_string;
}

輸出

This is constructor of generalized class
This is constructor of generalized class
This is constructor of specialized class (Only for characters)
This is constructor of generalized class

更新日期: 2019 年 7 月 30 日

765 次觀看

開啟你的 職業 生涯

完成課程以獲得認證

開始
廣告