What are Templates in C++?
Learn what C++ templates are: function and class templates, compile-time instantiation, type safety, the STL, and specialisation, with practical code examples.
Expected Interview Answer
Templates in C++ are a compile-time mechanism for writing generic code that works with any data type: you write a function or class once with a type parameter, and the compiler generates a specialised version for each type you actually use.
There are function templates and class templates, both introduced with the 'template<typename T>' syntax. When you call a function template or instantiate a class template with a concrete type, the compiler performs template instantiation, producing type-safe code with no runtime overhead. Templates power the Standard Template Library (vector, map, sort) and support advanced features like non-type parameters, template specialisation, and variadic templates.
- Write code once that works for many types
- Full type safety checked at compile time
- No runtime cost compared with hand-written type-specific code
- Foundation of the STL containers and algorithms
- Reduces duplication and maintenance burden
AI Mentor Explanation
A template is like a training drill written for 'any batter' rather than one named player. The drill describes footwork and timing generically, and when a specific batter — left-handed or right-handed — runs it, the coach adapts the exact same plan to that player. One reusable drill, automatically specialised for whoever steps up, without rewriting it for each individual.
Step-by-Step Explanation
Step 1
Declare the template parameter
Write 'template<typename T>' (or 'class T') before the function or class to introduce a type placeholder.
Step 2
Use T in the definition
Write the function or class body using T wherever a concrete type would normally appear.
Step 3
Instantiate with a type
Call the function or declare the class with a concrete type; the compiler deduces or takes T explicitly.
Step 4
Compiler generates code
For each distinct type used, the compiler produces a specialised, type-checked version of the code.
Step 5
Specialise when needed
Provide explicit or partial specialisations to give certain types custom behaviour.
What Interviewer Expects
- Difference between function templates and class templates
- The template<typename T> syntax
- That instantiation happens at compile time with no runtime cost
- Awareness of the STL as template-based
- Knowledge of template specialisation and type deduction
Common Mistakes
- Confusing templates with runtime generics like Java's type erasure
- Defining template implementations in a .cpp file, causing linker errors
- Assuming templates add runtime overhead
- Forgetting that each type used creates a separate instantiation
Best Answer (HR Friendly)
“Templates let you write one piece of code that works for many data types instead of copying it for each type. The compiler automatically builds the right version for whatever type you use, keeping the code short and type-safe.”
Code Example
#include <iostream>
using namespace std;
// Function template
template<typename T>
T maxOf(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template<typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T get() const { return value; }
};
int main() {
cout << maxOf<int>(3, 7) << "\n"; // 7
cout << maxOf(2.5, 1.5) << "\n"; // 2.5 (deduced)
Box<string> b("hello");
cout << b.get() << "\n"; // hello
}Follow-up Questions
- What is the difference between a function template and a class template?
- What is template specialisation?
- Why must template definitions usually live in header files?
- What are non-type template parameters?
- How do variadic templates work?
MCQ Practice
1. When does template instantiation happen?
The compiler generates a concrete version of the template for each type at compile time.
2. Which keyword introduces a type parameter in a template?
Both 'typename' and 'class' can introduce a template type parameter.
3. Why are template definitions typically placed in headers?
The full definition must be visible wherever the template is instantiated, or you get linker errors.
Flash Cards
What are the two main kinds of templates? — Function templates and class templates.
When is template code generated? — At compile time, once per distinct type used (template instantiation).
Do templates add runtime overhead? — No. They generate type-specific code at compile time, as efficient as hand-written code.
Where should template definitions go? — Usually in header files, so the definition is visible at every point of instantiation.