# Templates and template specialization

> How do templates work in C++? What are full and partial template specialization, and how do templates differ from macros and inheritance-based...

Canonical: https://www.internhack.in/learn/interview/cpp-interview/cpp-templates-specialization
Last updated: 2026-11-28

Difficulty: Advanced

## Question

How do templates work in C++? What are full and partial template specialization, and how do templates differ from macros and inheritance-based polymorphism?

## Answer

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.

## Code examples

### Primary template, full and partial specialization

```
#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.

## Key points

- Templates are instantiated at compile time; each set of arguments creates a separate concrete function or class.
- Full specialization replaces the template for one exact type; partial specialization for a family of types.
- Function templates cannot be partially specialized; use overloads or a class wrapper.
- if constexpr and C++20 concepts often replace specialization and SFINAE.
- Template bodies normally live in headers so the compiler can instantiate them.

## Common follow-up questions

- What is SFINAE?
- Why is std::vector<bool> considered problematic?
- What are C++20 concepts and how do they improve on enable_if?

## Interview tips

- Use the cookie cutter picture and contrast with virtual dispatch.
- Volunteer that function templates cannot be partially specialised.

## Concepts covered

templates, specialization, partial specialization, if constexpr, generic programming

Previous: [Friend functions and inline functions](https://www.internhack.in/learn/interview/cpp-interview/cpp-friend-inline-functions) · Next: [Smart pointers: unique_ptr and shared_ptr](https://www.internhack.in/learn/interview/cpp-interview/cpp-smart-pointers) · [All of C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)

## More C++ & STL questions

- [weak_ptr and breaking shared_ptr cycles](https://www.internhack.in/learn/interview/cpp-interview/cpp-weak-ptr-circular-references)
- [vector growth and iterator invalidation](https://www.internhack.in/learn/interview/cpp-interview/cpp-vector-growth-iterator-invalidation)
- [map vs unordered_map, and choosing an STL container](https://www.internhack.in/learn/interview/cpp-interview/cpp-map-vs-unordered-map-containers)
- [STL algorithms and priority_queue: sort, lower_bound, heaps](https://www.internhack.in/learn/interview/cpp-interview/cpp-stl-algorithms-priority-queue)
- [Lambdas and capture modes](https://www.internhack.in/learn/interview/cpp-interview/cpp-lambdas-captures)
- [The static keyword and its different meanings](https://www.internhack.in/learn/interview/cpp-interview/cpp-static-keyword)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)
