What Are Templates in C++?
C++ templates explained — instantiation, monomorphization, specialization and tradeoffs versus generics, with examples.
Expected Interview Answer
C++ templates let you write a function or class once with a placeholder type parameter, and the compiler generates a fully concrete, type-checked version for each specific type actually used, at compile time, via a process called template instantiation.
Unlike Java’s type erasure, C++ templates use monomorphization: for every distinct type argument the template is used with, the compiler stamps out a separate concrete copy of the code, so `Stack<int>` and `Stack<std::string>` become two independently compiled classes with no shared runtime representation. This means templates carry zero runtime overhead compared to hand-written type-specific code — the abstraction is fully resolved before the program runs. Function templates and class templates can also take non-type parameters (like array sizes) and can be specialized for particular types when the generic implementation isn’t suitable. The tradeoff is longer compile times and larger binaries (code bloat) from repeated instantiation, plus historically cryptic compiler error messages, which C++20 concepts were introduced to improve.
- Zero runtime overhead — fully resolved at compile time
- Type-safe generic code without manual duplication per type
- Supports non-type template parameters (e.g. fixed array sizes)
- Can be specialized for types needing custom behavior
AI Mentor Explanation
A tailor’s pattern for "kit in any team’s colors" is a single master design; every time a new team orders, the tailor cuts a fresh, fully finished uniform in that team’s specific colors rather than handing over a generic garment that gets dyed later. Each team ends up with its own completely separate, ready-made uniform, not a shared adjustable one. A C++ template works the same way: the compiler stamps out a distinct, fully compiled version of the code for every type used, rather than sharing one generic runtime representation.
Step-by-Step Explanation
Step 1
Declare a template
Use `template <typename T>` before a function or class definition.
Step 2
Write generic logic
Reference T as if it were a concrete type inside the function/class body.
Step 3
Trigger instantiation
The compiler generates a concrete version the first time the template is used with a specific type, e.g. `Stack<int>`.
Step 4
Specialize if needed
Provide a full or partial specialization for a type that needs different behavior than the generic version.
What Interviewer Expects
- Correct explanation of compile-time instantiation (monomorphization)
- Contrast with Java-style type erasure when asked
- Awareness of code-bloat and compile-time tradeoffs
- Mention of template specialization and non-type parameters
Common Mistakes
- Confusing C++ templates with Java generics (erasure vs instantiation)
- Believing a template exists as one shared class at runtime
- Not knowing templates must usually be defined in headers due to instantiation-per-translation-unit rules
- Forgetting that non-type template parameters (like `template<int N>`) are allowed
Best Answer (HR Friendly)
“Templates in C++ let you write a function or class once with a placeholder type, and the compiler creates a fully separate, optimized version of it for every actual type you use it with. That’s different from some other languages where the generic type information is stripped away at runtime — in C++, each version is a real, distinct piece of compiled code, so there’s no extra runtime cost, though it can mean longer compile times.”
Code Example
// Conceptually equivalent generic-style stack, shown in Java syntax:
class Stack<T> {
private java.util.List<T> items = new java.util.ArrayList<>();
void push(T item) { items.add(item); }
T pop() {
if (items.isEmpty()) throw new RuntimeException("empty stack");
return items.remove(items.size() - 1);
}
}
Stack<Integer> intStack = new Stack<>();
intStack.push(42);
Stack<String> strStack = new Stack<>();
strStack.push("hello");
// In C++, Stack<int> and Stack<std::string> are two separate compiled classes;
// in Java, both share one erased Stack class at runtime.Follow-up Questions
- What is template instantiation and when does it happen?
- How do C++ templates differ from Java generics at runtime?
- What is a non-type template parameter?
- What is template specialization and when would you use it?
MCQ Practice
1. How does the C++ compiler handle a template used with multiple types?
C++ templates use monomorphization — a distinct compiled version is generated per type argument.
2. What is a key tradeoff of C++ templates compared to type erasure?
Generating a separate copy per type can increase binary size and compile time, known as code bloat.
3. What can C++ templates accept that Java generics cannot?
C++ supports non-type template parameters like `template<int N>`, which Java generics do not allow.
Flash Cards
C++ template in one line? — A blueprint for generating fully concrete, type-specific code at compile time.
How are templates resolved? — Via instantiation (monomorphization) — a separate compiled version per type.
Main tradeoff? — Larger binaries and longer compile times from generating multiple type-specific copies.
What can specialize a template? — A full or partial specialization for a type needing custom behavior.