Difficulty: Advanced
How do templates work in C++? What are full and partial template specialization, and how do templates differ from macros and inheritance-based polymorphism?
Templates are the engine behind the entire STL, so understanding them explains how vector<int> and vector<string> come from one piece of source code. Let's start with the idea and then look at the specialization rules.
Think of a cookie cutter. A template is the cutter, not the cookie. You write the logic once, generically, for any type T, and the compiler stamps out a concrete version for each type you use. This process is called instantiation and happens at compile time, so 'max<int>' and 'max<double>' are two completely separate functions in the final binary. There is no runtime cost and no virtual dispatch, which is why templates are called static or compile-time polymorphism. The trade-offs: code bloat if you instantiate for many types, long compile times, and famously cryptic error messages (C++20 concepts improve this a lot).
Compare with macros: a macro is dumb text substitution with no type checking, no scoping, and nasty surprises like evaluating arguments twice. Templates are type-checked and scoped. Compare with inheritance: virtual functions decide at runtime through a vtable and need a common base class; templates decide at compile time and only need the operations to compile for the type (duck typing). Templates are faster but cannot store a heterogeneous collection in one vector.
Sometimes the generic version is wrong for a particular type. Specialization lets you provide a custom implementation. A full (explicit) specialization, written 'template<> struct Name<bool> {...}', replaces the template for one exact type. A partial specialization, like 'template<class T> struct Name<T*> {...}', customises a whole family, for example all pointer types. Important restriction: function templates cannot be partially specialized. Use overloading instead, or wrap the function in a class template with a static member and partially specialise that. The famous real-world example is std::vector<bool>, a full specialization that packs bits and, as a result, does not behave like other vectors (its operator[] returns a proxy object, not bool&), which is regarded as a design mistake.
Modern C++ gives you better tools than specialization for many cases: 'if constexpr' (C++17) branches at compile time inside a single template, and concepts (C++20) constrain what types are accepted with 'requires' clauses, so bad instantiations fail with a clear message. SFINAE with std::enable_if is the older mechanism you should recognise when reading legacy code.
A few more interview-friendly points. Template definitions generally must be visible in the header, since the compiler needs the body to instantiate it; putting them in a .cpp results in linker errors unless you explicitly instantiate. Template arguments can be non-type values (std::array<int, 5>), and C++17 class template argument deduction lets you write std::pair p(1, 2.5) without spelling the types. Finally, dependent names sometimes need 'typename' to tell the compiler that T::iterator is a type.
#include <iostream>
#include <string>
#include <type_traits>
template <class T>
struct Describe { static std::string name() { return "something"; } };
template <> // full specialization
struct Describe<bool> { static std::string name() { return "a bool"; } };
template <class T> // partial specialization for pointers
struct Describe<T*> { static std::string name() { return "pointer to " + Describe<T>::name(); } };
template <class T>
auto twice(T x) {
if constexpr (std::is_arithmetic_v<T>) return x * 2; // compile-time branch
else return x + x; // e.g. std::string
}
int main() {
std::cout << Describe<int>::name() << "\n";
std::cout << Describe<bool>::name() << "\n";
std::cout << Describe<bool*>::name() << "\n";
std::cout << twice(21) << " " << twice(std::string("ab")) << "\n";
}
Describe<bool*> matches the pointer partial specialization, which recursively uses the bool full specialization. if constexpr picks the right branch at compile time.
templates, specialization, partial specialization, if constexpr, generic programming