Template Specialization ใน C++
ฟังก์ชันมาตรฐาน เช่น sort() ใช้กับทุกประเภทข้อมูลได้ และทำงานเหมือนกันหมด แต่ถ้าต้องการพฤติกรรมพิเศษสำหรับประเภทข้อมูลเฉพาะ (แม้แต่ user-defined type) สามารถใช้ Template Specialization ได้
ตัวอย่าง
#include <iostream>
using namespace std;
template <class T>
void fun(T a) {
cout << "The main template fun(): " << a << endl;
}
// Specialization สำหรับ int
template<>
void fun(int a) {
cout << "Specialized Template for int type: " << a << endl;
}
int main() {
fun<char>('a'); // ใช้ main template
fun<int>(10); // ใช้ specialized version
fun<float>(10.14); // ใช้ main template
return 0;
}
ผลลัพธ์
The main template fun(): a Specialized Template for int type: 10 The main template fun(): 10.14
คำอธิบาย
template<> void fun(int a)คือ explicit specialization สำหรับ型int- เมื่อเรียก
fun<int>(10)จะใช้ specialized version แทน main template - ประเภทอื่นๆ (char, float, ฯลฯ) ยังใช้ main template ตามปกติ
ประโยชน์
- ปรับพฤติกรรมได้เฉพาะบาง型โดยไม่กระทบ型อื่น
- ใช้ได้กับ built-in types และ user-defined types
- รองรับ full specialization และ partial specialization (สำหรับ class templates)