Templates let you write generic code parameterized by types or values—the mechanism behind std::vector<T> and std::sort.
Function template
template <typename T>
T maxValue(T a, T b) {
return (a < b) ? b : a;
}
The compiler generates concrete functions for each used type—compile-time instantiation, not runtime JVM generics.
Important interview questions and answers
- Q: Templates vs virtual functions?
A: Templates resolve at compile time per type (monomorphization); virtual uses runtime dispatch on inheritance. - Q: Template definitions in headers?
A: Instantiations need full definition visible—typically templates live in headers.
Self-check
- When is a template instantiated?
- Why are templates often header-only?
Tip: Template error messages are verbose—start with simple function templates before class templates.
Interview prep
- Templates vs virtual?
Templates instantiate at compile time per type; virtual functions use runtime dispatch on inheritance.
- Templates in headers?
Full template definitions must be visible at instantiation sites—typically in headers.