Interview Q&A · C++ · 12 questions in this topic
Templates & Generic Programming — C++ Interview Q&A
Compile-time genericity — function/class templates, specialization, variadics, SFINAE vs concepts, and template costs. Part of Templates & Generics · 213 questions in the C++ bank.
What is a template and what is instantiation?
Answer
A template is a compile-time blueprint parameterized on types or values; instantiation is the compiler generating a concrete class/function for a given argument set. Function templates deduce arguments from calls; class templates (pre-C++17) need explicit arguments, with CTAD now deducing them in many cases.
Each distinct argument set produces separate code — the source of both zero-cost abstraction and code bloat.
Example
template<class T> T max2(T a, T b) { return a < b ? b : a; } max2(1, 2); // T=int deduced max2(1.5, 2.5); // T=double: separate instantiation
💡 Blueprint vs generated code is the one-line mental model for all template questions.
Function template vs class template — what differs?
Answer
Function templates deduce from call arguments and participate in overload resolution; they cannot be partially specialized (overload instead). Class templates define parameterized types, support partial and full specialization, hold static members per instantiation, and guide CTAD.
Variable templates (C++14) and alias templates extend the same idea to values and names.
Example
template<class T> struct Box { T value; }; // class template template<class T> void f(T); // function template: deduction from call Box<int> b{5};
What is template specialization (full and partial)?
Answer
Full specialization provides a custom implementation for one exact argument set (template<> class Vec<bool>). Partial specialization customizes for a pattern (template<class T> class Ptr<T*> for all pointers). The most specialized match wins.
Use it for optimizations (vector<bool>, pointer traits), type traits, and policy customization — not as a substitute for overloading function templates.
Example
template<class T> struct Tag { static constexpr char v = 'g'; }; template<> struct Tag<int> { static constexpr char v = 'i'; }; // full template<class T> struct Tag<T*> { static constexpr char v = 'p'; }; // partial
💡 Full pins exact types, partial pins patterns — that distinction answers most specialization follow-ups.
What are variadic templates and parameter packs?
Answer
Variadic templates accept any number of arguments via a parameter pack (Args...). C++17 fold expressions process packs concisely ((args + ...)), replacing pages of recursive unpacking. Packs also forward perfectly (std::forward<Args>(args)...) into factories like make_unique and emplace.
sizeof...(Args) gives the pack size at compile time.
Example
template<class... Args> int sum(Args... args) { return (args + ... + 0); } // fold sum(1, 2, 3); // 6
💡 Mention fold expressions unprompted — it signals genuinely modern (C++17+) template knowledge.
What is SFINAE and what replaced it?
Answer
SFINAE (Substitution Failure Is Not An Error) drops overloads/specializations whose template substitution fails, instead of erroring — the pre-C++20 mechanism behind enable_if-constrained APIs. It works but produces miserable diagnostics.
C++20 concepts and requires-clauses express the same constraints readably with far better errors, and should be the default choice in new code.
Example
#include <type_traits> // classic SFINAE: only for integral types template<class T, std::enable_if_t<std::is_integral_v<T>, int> = 0> void f(T) {}
💡 Know what SFINAE stands for and name concepts as its replacement — that pairing is the expected answer shape.
What is a concept (C++20) and why is it better than SFINAE?
Answer
A concept is a named compile-time requirement on template arguments, checked at the call site with clear errors. Unlike SFINAE, constraints are part of the interface: overloads order by subsumption, diagnostics name the failed requirement, and intent is readable.
The standard ships concepts like std::integral, std::ranges::range and std::convertible_to; requires-expressions define new ones inline.
Example
#include <concepts> template<std::integral T> T twice(T x) { return x * 2; } // twice(2.5); // clear error: double does not satisfy integral
💡 Contrast readable concept errors with pages of enable_if substitution spew — every interviewer has felt that pain.
Why must template definitions usually live in headers?
Answer
The compiler needs the full definition at the point of instantiation to generate code — a declaration alone is not enough. So function templates, class template members and (usually) concepts live in headers, with explicit instantiation definitions as the opt-out for closed type sets and faster builds.
Exported templates were tried (export template) and removed; modules (C++20) are the modern answer to the header cost.
Example
// vec.h: full definition visible to every includer template<class T> struct Vec { void push(T); /* ... */ }; // explicit instantiation (closed set, faster builds): // template struct Vec<int>;
What is template type deduction for forwarding references?
Answer
For template<class T> f(T&&), an lvalue argument deduces T as T& (reference collapsing keeps it an lvalue) while an rvalue deduces T as plain T (binding as rvalue). Combined with std::forward<T>, the function perfectly forwards the original category — the foundation of emplace, make_unique and wrapper APIs.
This single rule explains why one signature handles both copies and moves.
Example
template<class T> void wrap(T&& x) { target(std::forward<T>(x)); // lvalue stays lvalue, rvalue stays movable }
What is the difference between templates and macros?
Answer
Templates are type-checked, scope-aware, debugger-visible C++ evaluated at compile time with proper semantics. Macros are textual substitution by the preprocessor with no type checking, no scope, surprising double-evaluation, and unreadable errors.
Prefer constexpr/consteval functions, inline variables and templates over macros; reserve macros for conditional compilation and unavoidable boilerplate.
Example
#define SQUARE(x) ((x) * (x)) // SQUARE(i++) expands to ((i++) * (i++)) — double increment! template<class T> constexpr T square(T x) { return x * x; } // safe
What is template code bloat and how do you control it?
Answer
Each distinct instantiation emits its own code, so N types × M templates can explode binary size. Control it by hoisting type-independent logic into non-template bases/helpers (.cpp-implemented), explicit instantiation for closed sets, extern templates to instantiate once, and small shared implementation functions.
Thin-template / thick-implementation is the classic pattern: template shell, non-template core.
Key points
- 1Hoist — non-template base with the shared logic.
- 2extern template — declare once, define in one TU.
- 3Explicit instantiation — closed type sets only.
Example
// header: extern template declaration // extern template class std::vector<MyType>;
What is `typename` for inside templates (besides declaring type parameters)?
Answer
Inside a template, dependent names (those depending on a template parameter) are assumed to be values, not types — typename tells the compiler a qualified dependent name is a type (typename T::value_type). Since C++20 many contexts deduce this, but member type access in generic code still needs it.
The sister keyword template disambiguates dependent member templates (p.template get<int>()).
Example
template<class T> void f(const T& c) { typename T::value_type v{}; // typename: this names a type }
💡 Dependent name defaults to value, typename overrides to type — that single rule explains every typename sighting.
What is two-phase name lookup for templates?
Answer
Templates are checked twice: phase one (at definition) resolves non-dependent names immediately; phase two (at instantiation) resolves dependent names with the template arguments plus ADL from the instantiation context. Consequences: non-dependent names never see later declarations, and dependent calls pick up ADL-visible overloads from argument namespaces.
This is why moving a helper above/below a template can change behavior, and why ADL surprises cluster around templates.
Example
void g(int); template<class T> void h(T t) { g(t); // dependent: phase-two lookup, ADL applies // non-dependent names here bound already at phase one }
Recommended resourcesAffiliate links · may earn us a commission