C++ Templates
🧩 C++ Templates
C++ Templates allow you to write generic code that works with any data type.
Instead of writing the same function or class multiple times for different types, you write it once using templates.
Introduced to support generic programming.
1. Why Use Templates?
-
Avoid code duplication
-
Type-safe generic programming
-
Reusable and flexible code
-
Widely used in STL (vector, map, stack, etc.)
2. Function Templates
🔸 Basic Syntax
Usage:
✔ Compiler generates separate versions for each type
3. Template with Multiple Types
Usage:
4. Class Templates
🔸 Basic Example
Usage:
5. Template with Default Type
Usage:
6. Template Specialization
Allows custom behavior for a specific type.
7. Function Template Specialization
8. Templates and STL (Real Use)
✔ STL is built entirely on templates
9. typename vs class
and
✔ Both are identical in templates
✔ typename preferred in modern C++
10. Limitations of Templates
-
Compilation time increases
-
Error messages can be complex
-
Code bloat (multiple instantiations)
❌ Common Mistakes
✔ Fix:
🔁 Templates vs Function Overloading
| Templates | Overloading |
|---|---|
| Generic | Specific |
| One definition | Multiple definitions |
| Compile-time | Compile-time |
| Type-safe | Type-safe |
📌 Summary
-
Templates enable generic programming
-
Support functions and classes
-
Used heavily in STL
-
Reduce code duplication
-
Compile-time type safety
