ใน 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