CurriculumTemplates
Templates
<strong>Templates</strong> allow you to write functions or classes that operate on generic types. Instead of writing separate code for <code>int</code>, <code>double</code>, and <code>string</code>, you write one blueprint using a placeholder type (like <code>T</code>). The compiler automatically generates the exact versions you need.
01The Problem: Function Overloading
Without templates, if you want a function to handle different types, you have to write it multiple times (Function Overloading). This is tedious and violates the DRY (Don't Repeat Yourself) principle.
main.cpp
Terminal
Waiting for execution...
02Function Templates
With a template, you write the logic ONCE using a placeholder type
T. When you call add(10, 5), the compiler secretly writes the int version for you!main.cpp
Terminal
Waiting for execution...
03Multiple Template Types
You aren't restricted to just one placeholder. You can use
T, U, V, etc., to allow mixing different types in the same generic function.main.cpp
Terminal
Waiting for execution...
04Class Templates
Classes can be templates too! This is exactly how
std::vector<int> works. You create a generic box that can hold ANY type.main.cpp
Terminal
Waiting for execution...
05Template Specialization
Sometimes a generic template works for 99% of types, but you want to do something completely different for one specific type (like
std::string). This is called Template Specialization.main.cpp
Terminal
Waiting for execution...
06Non-Type Template Parameters
Templates don't just take types; they can also take actual VALUES (like an integer) evaluated at compile-time! This is how
std::array<int, 5> sets its size without using dynamic heap memory.main.cpp
Terminal
Waiting for execution...
AI Tutor
Templates are the absolute core of modern C++. The entire Standard Template Library (STL) — vectors, maps, algorithms — is built on templates. Without them, you would have to write a custom vector class for every single data type in existence.