Skip to content

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

TopicDescription
Function TemplatesGeneric functions
Class TemplatesGeneric classes (Box<T>)
Template SpecializationHandle edge cases
C++20 ConceptsConstrain templates

Templates vs Macros vs void*

ApproachType-safePerformanceDebugging
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


Learning Path

  1. 🔧 Function Templates — Bắt đầu đơn giản
  2. 📦 Class Templates — Generic containers
  3. 🎯 Specialization — Edge cases
  4. 🚀 C++20 Concepts — Modern constraints

"Templates are the foundation of C++ generic programming. They enable type-safe, zero-overhead abstractions." — Bjarne Stroustrup