Core Module
12 min forge
C++ Templates
Mastering generic programming to write code that works with any data type.
C++ Templates
π What is it
Templates are a powerful feature in C++ that allow you to write generic code. They are the foundation of the Standard Template Library (STL). You can define functions or classes that work with any data type specified as a template parameter.
β‘ When to use
Use templates when you need to perform the same operations on different data types (e.g., a swap function or a Stack class).
π§ Time complexity
- Compilation: Increased (templates are instantiated at compile-time).
- Runtime: $O(1)$ overhead (same as hand-written code for a specific type).
π» Code example
cpp Standardtemplate <typename T> T myMax(T x, T y) { return (x > y) ? x : y; } int main() { std::cout << myMax<int>(3, 7); // 7 std::cout << myMax<double>(3.0, 7.0); // 7.0 }
β Common mistakes
- Bloat: Large templates can significantly increase binary size (Code Bloat).
- Compiler Errors: Template errors can be notoriously difficult to read and debug.
- Not putting template definitions in header files (they must be visible to the compiler at instantiation).