Giao diện
Part 5: Templates Advanced
Templates là trái tim của Generic Programming trong C++ — viết code một lần, dùng cho mọi type.
DRY — Don't Repeat Yourself
Vấn đề: Code Duplication
cpp
// ❌ Phải viết riêng cho mỗi type
int addInt(int a, int b) { return a + b; }
double addDouble(double a, double b) { return a + b; }
float addFloat(float a, float b) { return a + b; }
long addLong(long a, long b) { return a + b; }
// ... và còn tiếp!Giải pháp: Templates
cpp
// ✅ Một function cho TẤT CẢ types
template<typename T>
T add(T a, T b) {
return a + b;
}
// Compiler tự động generate code cho từng type khi cần
int main() {
int x = add(1, 2); // Generates add<int>
double y = add(1.5, 2.5); // Generates add<double>
std::string z = add(std::string("Hello "), std::string("World"));
return 0;
}Tại sao Templates?
┌─────────────────────────────────────────────────────────────────┐
│ TEMPLATES POWER │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. CODE REUSE │
│ Write once, use with any type │
│ │
│ 2. TYPE SAFETY │
│ Compile-time type checking (không như void*) │
│ │
│ 3. ZERO OVERHEAD │
│ Compiler generates specialized code — no runtime cost │
│ │
│ 4. STL FOUNDATION │
│ vector<T>, map<K,V>, sort(), find() — all templates! │
│ │
└─────────────────────────────────────────────────────────────────┘Module Structure
📘 Core Templates
| Topic | Description |
|---|---|
| Function Templates | Generic functions |
| Class Templates | Generic classes (Box<T>) |
| Template Specialization | Handle edge cases |
| C++20 Concepts | Constrain templates |
Templates vs Macros vs void*
| Approach | Type-safe | Performance | Debugging |
|---|---|---|---|
| Templates | ✅ Compile-time check | ✅ Optimized | 🔸 Complex errors |
| Macros | ❌ No type check | ✅ Inline | ❌ Very hard |
| void* | ❌ Runtime cast | ❌ Indirection | ❌ Runtime crashes |
📌 HPN Standard
Templates là lựa chọn mặc định cho generic programming trong C++. Chỉ dùng macros cho preprocessor tasks (guards, platform detection).
Prerequisites
📋 YÊU CẦU
- ✅ Class Anatomy
- ✅ Functions
- ✅ Basic understanding của STL containers
Learning Path
"Templates are the foundation of C++ generic programming. They enable type-safe, zero-overhead abstractions." — Bjarne Stroustrup