Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Đặc biệt hóa Template (Template Specialization) trong C++


Template cho phép viết code tổng quát cho nhiều kiểu dữ liệu. Đặc biệt hóa template (specialization) cho phép định nghĩa phiên bản riêng cho một kiểu cụ thể.

Đặc biệt hóa hàm

#include <iostream>
using namespace std;

template<typename T>
void my_function(T x) {
    cout << "Template chung: " << x << endl;
}

template<>
void my_function(char x) {
    cout << "Template đặc biệt cho char: " << x << endl;
}

int main() {
    my_function(10);
    my_function(25.36);
    my_function('F');
    my_function("Hello");
}

Kết quả

Template chung: 10
Template chung: 25.36
Template đặc biệt cho char: F
Template chung: Hello

Đặc biệt hóa lớp

template<typename T>
class MyClass {
public:
    MyClass() { cout << "Lớp chung\n"; }
};

template<>
class MyClass<char> {
public:
    MyClass() { cout << "Lớp đặc biệt cho char\n"; }
};

int main() {
    MyClass<int> a;
    MyClass<float> b;
    MyClass<char> c;
    MyClass<string> d;
}

Kết quả

Lớp chung
Lớp chung
Lớp đặc biệt cho char
Lớp chung