Interview Q&A · C++ · 12 questions in this topic

Templates & Generic Programming — C++ Interview Q&A

All C++ topics

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

Example.cppcpp
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

Example.cppcpp
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

Example.cppcpp
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.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits