ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจความเชี่ยวชาญด้านเทมเพลตใน 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