What is a Template in C++?
Learn what templates are in C++, how function and class templates work, compile-time instantiation, specialization, and C++20 concepts.
Expected Interview Answer
A template is a C++ language feature that lets you write a single function or class definition parameterized over one or more types, letting the compiler generate a specialized version for each concrete type actually used.
There are function templates (e.g., a generic `max(T a, T b)`) and class templates (e.g., `std::vector<T>`), both declared with `template<typename T>` before the definition. The compiler performs template instantiation at compile time, generating a distinct version of the code for each type used, which means there is zero runtime overhead versus writing that code by hand for each type, unlike using a base class with virtual functions. Templates can be constrained further through specialization, allowing a different implementation for specific types, and modern C++ adds concepts (C++20) to express readable compile-time requirements on template parameters instead of relying on cryptic error messages. Because instantiation happens per translation unit, template definitions typically live in header files.
- Enables generic, type-safe code reused across many types
- Zero runtime overhead — resolved entirely at compile time
- Powers the STL's containers and algorithms
- Template specialization allows custom behavior for specific types
- Concepts (C++20) improve error messages and express clear constraints
AI Mentor Explanation
A template is like a standard net-practice drill sheet that works for any bowling style — pace, spin, or swing — the coach just fills in which style before the session starts. Once filled in for a specific style, the drill becomes a fully concrete session tailored exactly to that bowler, generated fresh each time rather than reused generically at runtime.
Step-by-Step Explanation
Step 1
Declare the template
Write `template<typename T>` (or `class T`) above a function or class to parameterize it over a type.
Step 2
Write generic logic
Implement the function or class body using `T` wherever a concrete type would normally appear.
Step 3
Compiler instantiates on use
When called or instantiated with a concrete type like `int` or `std::string`, the compiler generates a specialized version at compile time.
Step 4
Specialize when needed
Provide a full or partial specialization to give a custom implementation for specific types that need different behavior.
Step 5
Constrain with concepts (C++20)
Use concepts to express readable requirements on `T`, producing clearer compiler errors than raw template metaprogramming.
What Interviewer Expects
- Distinguishes function templates from class templates
- Explains compile-time instantiation and zero runtime overhead
- Knows templates typically live in header files
- Can describe template specialization with an example
- Aware of concepts (C++20) improving template constraint readability
Common Mistakes
- Confusing templates with runtime polymorphism (virtual functions)
- Putting template definitions only in a `.cpp` file, causing linker errors
- Thinking templates add runtime overhead like virtual dispatch
- Not knowing what template specialization is or when to use it
- Overusing templates for cases where a simple function overload suffices
Best Answer (HR Friendly)
“A template is a way to write one piece of code in C++ that works with many different data types, similar to a fill-in-the-blank form that adapts to whatever information you provide. It saves developers from writing the same logic repeatedly for each type.”
Code Example
#include <iostream>
// Function template
template<typename T>
T maxValue(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template<typename T>
class Box {
private:
T value;
public:
explicit Box(T v) : value(v) {}
T get() const { return value; }
};
int main() {
std::cout << maxValue(3, 7) << "\n"; // 7 (T = int)
std::cout << maxValue(2.5, 1.1) << "\n"; // 2.5 (T = double)
Box<std::string> b("hello");
std::cout << b.get() << "\n"; // hello
return 0;
}Follow-up Questions
- What is the difference between a function template and a class template?
- Why do template definitions usually live in header files?
- What is template specialization and when would you use it?
- How do C++20 concepts improve on plain templates?
- How do templates achieve zero runtime overhead compared to virtual functions?
MCQ Practice
1. What does the compiler do when a template is used with a specific type?
Templates are resolved through compile-time instantiation, generating a distinct version of the code for each concrete type used, with no runtime overhead.
2. Where do template definitions typically need to live, and why?
Because each translation unit that uses a template needs to instantiate it, template definitions typically must be visible in headers rather than hidden in a `.cpp` file.
3. What does template specialization allow?
Specialization lets you override the generic template implementation with tailored code for particular types that need different behavior.
Flash Cards
What keyword introduces a template? — `template<typename T>` (or `template<class T>`), placed before a function or class definition.
When is a template instantiated? — At compile time, when it is used with a concrete type.
Why do templates usually live in header files? — Because each translation unit using the template needs its full definition to instantiate it.
What is template specialization? — Providing a custom implementation of a template for a specific type instead of the generic version.