Templates and Generic Programming#
Based on C++ Primer, 5th ed., Chapter 16 (Templates and Generic Programming), this post summarizes function and class template instantiation, template argument deduction, forwarding references (T&&) and reference collapsing, variadic templates (Args...) and how emplace_back works under the hood, and template specialization.
1. Function and Class Template Fundamentals#
- Template Instantiation: A template itself is a blueprint, not executable code. When you invoke
compare(1, 0)or declarestd::vector<std::string>, the compiler substitutes the concrete type forTand instantiates a type-specific version of the function or class. - Why Must Template Declarations and Definitions Live in Header Files (
.h)?- For an ordinary function, the compiler only needs the declaration to compile a call site, and the linker later links the
.oobject file. To instantiate a template, however, the compiler must see the full template body at the call site so it can generate code for the concrete type.
- For an ordinary function, the compiler only needs the declaration to compile a call site, and the linker later links the
1. Type Parameters (typename / class) and Non-type Template Parameters#
In addition to type parameters (typename T), templates can take non-type template parameters representing compile-time constant expressions (constexpr integers, pointers, or references):
// 1. Type template parameter (typename and class are 100% interchangeable here)
template <typename T>
int compare(const T &v1, const T &v2) {
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}
// 2. Non-type Template Parameters (unsigned N, unsigned M):
// Binds references to arrays directly without pointer decay
template <unsigned N, unsigned M>
int compare(const char (&p1)[N], const char (&p2)[M]) {
return strcmp(p1, p2);
}
int r = compare("hi", "mom"); // At the call site, compiler deduces N as 3 and M as 4, instantiating compare<3, 4>
2. Dependent Type Names and the Mandatory typename Rule#
When accessing a name nested inside a template type parameter such as T::Bar, the compiler does not know before instantiation whether that name refers to a nested type or a non-type member such as a static data member, static member function, or enumerator. For example, the grammatical meaning of T::Bar * x; changes completely depending on T:
int x = 10;
template <typename T>
void func() {
T::Bar * x; // Pointer variable declaration, or multiplication expression?
}- If
struct A { using Bar = int; };is passed (Baris a nested type): it meansint * x;, a pointer variable declaration (*is the pointer declarator). - If
struct B { static int Bar; };is passed (Baris astaticvariable): it multipliesB::Barandxas a multiplication expression (*is the multiplication operator).
To resolve this ambiguity, C++ assumes by default that an unadorned T::... is not a type. To tell the compiler that T::... names a type, you must prefix it with typename; class cannot be used here:
template <typename Container>
// 'typename' is required to inform the compiler that these dependent names are types
typename Container::value_type top_element(const Container &c) {
typename Container::const_iterator it = c.begin();
return *it;
}2. Template Argument Deduction & Reference Collapsing#
When using a function template or class template (via C++17 CTAD) without explicitly specifying <T>, leaving it to the compiler to deduce T from the passed arguments, the process is called Template Argument Deduction. For example, when calling compare(1, 0) instead of compare<int>(1, 0), a function template’s deduction rule splits into three cases depending on the parameter declaration form (T, T& / const T&, T&&):
| Function Template Parameter Form | Preserves const? | Array/Function Decay? | Key Behavior |
|---|---|---|---|
By Value (T) | Strips top-level const | Arrays/functions undergo pointer decay (T*) | Same as Copying Objects: creating an independent copy ignores top-level const on the argument. |
By Reference (T& / const T&) | Preserves low-level const | No pointer decay; arrays remain array references (T (&)[N]) | Passing two string literals of different lengths ("hi", "world") to compare(const T&, const T&) fails to compile (T is deduced as char[3] vs. char[6]). |
Forwarding Reference (T&&) | Preserves both value category and const | No pointer decay for lvalue arrays/functions | Via the special lvalue deduction rule and Reference Collapsing below, binds to both lvalues and rvalues while preserving their exact types. |
Forwarding References (T&&) and Reference Collapsing Rules#
Template wrapper functions like make_unique and emplace_back, which receive parameters and pass them on to another function, must preserve both the constness and value category of each argument with zero copy overhead. Every other parameter form fails this requirement:
| Function Template Parameter Declaration | Why It Fails for Perfect Forwarding |
|---|---|
T arg | Creates a value copy immediately, wasting performance and losing reference identity |
T& arg | Cannot bind to rvalues like 42 or "hello", causing a compile error |
const T& arg | Binds to both lvalues and rvalues, but forces const onto the parameter so forwarding to non-const references inside the template function is blocked, and rvalues invoke expensive copy constructors instead of move constructors |
To account for both lvalues and rvalues, manually overloading const T& and T&& for every parameter would require $2^N$ functions for $N$ parameters. C++11 solves this in a single function template using T&& attached directly to a deduced template parameter T, known as a Forwarding Reference:
- Special lvalue Deduction Rule for
T&&([temp.deduct.call]):- Under ordinary template deduction, passing an
intlvalue would deduceTasint, turning the parameter intoint&&and failing to compile because an rvalue reference cannot bind to an lvalue. - To solve this, C++11 introduced a dedicated deduction rule: when a function template parameter has the exact form
T&&, passing an rvalue deducesTasint, whereas passing an lvalue deducesTas an lvalue reference typeint&. - Strict Form Requirement: This rule activates only when
Tis a deduced parameter of that function template itself in the exact unadorned formT&&. Adding qualifiers or wrappers likeconst T&&orstd::vector<T>&&, or using a class template’sTin a constructor parameter, disables the rule and leaves an ordinary rvalue reference.
- Under ordinary template deduction, passing an
- Reference Collapsing Rules:
- When
Tis deduced asint&, substituting intoT&&producesint& &&, which the compiler collapses via these rules:T& &,T& &&,T&& &→ all collapse toT&: any lvalue reference&wins.T&& &&→ collapses toT&&: only when both are rvalue references.
- When
Call Argument (int example) | Deduced T | Uncollapsed T&& | Final Collapsed Parameter Type | Result of std::forward<T>(ARG) |
|---|---|---|---|---|
Non-const lvalue | int& | int& && | int& | Restores int&, preserving non-const lvalue |
const lvalue | const int& | const int& && | const int& | Restores const int&, preserving const lvalue |
rvalue (42) | int | int && | int&& | Restores int&&, preserving rvalue |
Inside the function body, the named parameter ARG is always an lvalue expression, but whether T was deduced as a reference type int& or a value type int records whether the original argument was an lvalue or an rvalue. std::forward<T>(ARG) inspects T to restore that exact value category, completing Perfect Forwarding. For code examples, see Copy Elision & Move Semantics: std::move vs. std::forward.
3. Variadic Templates (Args...) and emplace_back#
A variadic template accepts zero or more template type parameters and function arguments. Depending on where ... appears, placing ... before a name packs elements together, whereas placing ... after a pattern expands them:
...Before a Name — Packing (Parameter Pack Declaration):- Template Parameter Pack (
typename... Args): Packs zero or more types intoArgs. - Function Parameter Pack (
Args&&... args): Packs zero or more function arguments intoargs. Despite the word “Function” in its name, it cannot be used in ordinary non-template functions and is valid only in function templates (or member functions of variadic class templates) that reference a Template Parameter Pack.
- Template Parameter Pack (
...After an Expression — Unpacking (Pack Expansion):PATTERN...: Replicates the entire pattern to the left of...for each element in the pack, separated by commas,.- For example,
args...expands toarg1, arg2, whilestd::forward<Args>(args)...expands tostd::forward<T1>(arg1), std::forward<T2>(arg2). Placing...inside the parentheses asstd::forward<Args>(args...)is a compile error because it tries to pass multiple arguments into a singlestd::forwardcall (std::forward<T1, T2>(arg1, arg2)).
sizeof...(Args)Operator: Returns the number of elements in a pack at compile time.
1. Recursive Variadic Function Pattern#
Variadic functions typically process the first argument t and recursively pass the remaining pack rest.... A non-variadic base-case overload must be declared in scope before the variadic template to terminate the recursion:
#include <iostream>
// 1. Base Case (must be declared before the variadic template): prints the final argument and ends recursion
template <typename T>
std::ostream& print(std::ostream &os, const T &t) {
return os << t;
}
// 2. Variadic Function Template: prints first argument t, then recursively expands rest...
template <typename T, typename... Args>
std::ostream& print(std::ostream &os, const T &t, const Args&... rest) {
os << t << ", ";
return print(os, rest...); // Pack expansion peels off one argument at each step
}2. Pack Expansion and How emplace_back Works Under the Hood#
Standard container emplace_back and std::make_unique construct elements directly in target memory without temporary objects by combining variadic forwarding references (Args&&...) with pack expansion of std::forward<Args>(args)...:
template <typename T>
class Vec {
public:
// Packs any number of constructor arguments into Args&&..., then expands the full std::forward pattern
template <typename... Args>
void emplace_back(Args&&... args) {
chk_n_alloc(); // Ensure capacity is available and reallocate if full
alloc.construct(first_free++, std::forward<Args>(args)...);
}
};
// Example: Actual code instantiated by the compiler for vec.emplace_back(10, 'c') (Args deduced as int, char)
// void emplace_back(int&& arg1, char&& arg2) {
// chk_n_alloc();
// alloc.construct(first_free++, std::forward<int>(arg1), std::forward<char>(arg2));
// }
4. Template Specialization#
When a generic primary template definition is unsuitable or inefficient for a specific type or type pattern, you can define a dedicated implementation via Template Specialization.
1. Why Are the Angle Brackets Empty in template <> for Full Specialization?#
- Primary Template (
template <typename T>): Indicates that 1 unbound template type parameterTremains. - Explicit Full Specialization (
template <>): BecauseThas been bound to a concrete type such asstd::stringorint, 0 unbound template parameters remain, leaving<>empty. Omittingtemplate <>while keeping<int>on the function name is a syntax error.
// 1. Primary Template: converts any type C into a std::string via ostringstream
template <typename C>
inline std::string Stringify(const C &value) {
std::ostringstream o;
o << value;
return o.str();
}
// 2. Explicit Full Specialization:
// C is bound to std::string, so 0 unbound template parameters remain -> template <>
template <>
inline std::string Stringify<std::string>(const std::string &s) { // <std::string> can be omitted if deducible from parameters
return "\"" + s + "\""; // Wrap strings in quotes
}2. Full Specialization vs. Partial Specialization#
Depending on whether any unbound template parameters remain, specialization falls into two categories:
- Full Specialization (
template <>): Binds every template parameter of the primary template to a concrete type or value so that 0 unbound parameters remain, such asstruct hash<int64_t>orstruct Map<std::string, int>. - Partial Specialization (
template <...>): Narrows the primary template while leaving one or more template parameters unbound, so those remaining parameters are still listed insidetemplate <...>. This takes two common forms:- Fixing only a subset of parameters: Given
template <typename K, typename V> struct Map, fixingKtostd::stringwhile leavingVunbound astemplate <typename V> struct Map<std::string, V>. - Constraining a type pattern: Specializing for all pointers (
T*), references (T&,T&&), or fixed-size arrays (T[N]) rather than a single concrete type, such astemplate <typename T> struct hash<T*>.
- Fixing only a subset of parameters: Given
Support across function templates and class templates differs as follows:
| Aspect | Function Templates (template <typename T> void f(T)) | Class / Struct Templates (template <typename T> struct Foo) |
|---|---|---|
| Full Specialization | ✅ template <> int compare(const char* const &p1, const char* const &p2) | ✅ template <> struct hash<int64_t> |
| Partial Specialization | ❌ Use function overloading instead | ✅ Supports both subset parameter binding and T*, T&, T[N] pattern specialization |
- Why can’t we just put pointer logic in the primary
struct hashor define anotherstruct hashwithout<T*>?- Value/object types (
T), pointer types (T*), and array types (T[N]) require completely different hashing logic (e.g., casting a pointer address viareinterpret_cast<size_t>fails to compile for non-pointer objects likestd::string). - Unlike functions, classes and structs cannot be overloaded. Defining another
template <typename T> struct hashwithout<T*>causes aredefinition of 'hash'compile error; the<T*>pattern suffix tells the compiler to select this specialization specifically for pointer types.
- Value/object types (
- Partial specializations can have more template parameters than the primary template:
- Although the primary template
template <typename T> struct hashhas only 1 parameter (T), partially specializing for a fixed-size array patternT[N]requires 2 unbound parameters (the element typeTand array lengthN):template <typename T, size_t N> struct hash<T[N]>.
- Although the primary template
- Compiler Matching Priority: 1st: Full Specialization (
hash<int64_t>) $\rightarrow$ 2nd: Partial Specialization (hash<T*>,hash<T[N]>) $\rightarrow$ 3rd: Primary Template (hash<T>) (most specific match wins).
// Complete structure combining Primary + Full + Partial Specializations (T*, T[N])
// [1] Primary Template (fallback for general types T)
template <typename T>
struct hash {
size_t operator()(const T &x) const { return x.CustomHash(); }
};
// [2] Full Specialization (T fixed to int64_t -> 0 unbound parameters remain, so template <>)
template <>
struct hash<int64_t> {
size_t operator()(int64_t x) const { return static_cast<size_t>(x); }
};
// [3] Partial Specialization #1: all pointer types (T* pattern -> pointee T still unbound, so template <typename T>)
template <typename T>
struct hash<T*> {
size_t operator()(T *x) const { return reinterpret_cast<size_t>(x); }
};
// [4] Partial Specialization #2: all fixed-size array types (T[N] pattern -> 2 unbound parameters T and N)
template <typename T, size_t N>
struct hash<T[N]> {
size_t operator()(const T (&arr)[N]) const {
size_t total = 0;
hash<T> elem_hasher;
for (size_t i = 0; i < N; ++i) total ^= elem_hasher(arr[i]);
return total;
}
};3. Function Template Specialization (template <>) vs. Function Overloading: When to Use Which?#
To customize a function for a specific type, you can either write an explicit specialization (template <>) or a plain non-template function overload. For example, suppose we want Stringify to wrap C-style strings (const char*) in double quotes:
// Primary Template: converts any type C into a std::string via ostringstream
template <typename C>
std::string Stringify(const C &value) {
std::ostringstream o;
o << value;
return o.str();
}
// Approach 1: template <> Explicit Specialization (tied to the Primary Template above)
template <>
std::string Stringify<const char*>(const char* const &s) { // const C& with C substituted as const char*
return "\"" + std::string(s) + "\"";
}
// Approach 2: Plain Function Overload (standalone non-template function without template <>)
std::string Stringify(const char *s) {
return "\"" + std::string(s) + "\"";
}The two approaches behave differently depending on how the function is called:
- When
<...>is explicitly specified at the call site (Stringify<const char*>("hello")):- Writing
<const char*>after the function name instructs the compiler to exclude plain non-template overloads (Approach 2) completely and search only amongtemplatedeclarations. Thus, if you only wrote Approach 2, it is skipped and the Primary Template gets called ("hello"), whereas Approach 1 (template <>) belongs to thattemplateand gets called as expected ("\"hello\"").
- Writing
- Why is plain function overloading still preferred over
template <>for ordinary calls without<...>(Stringify("hello"))?- No Implicit Conversions or Pointer Decay on Template Specializations:
- Approach 1 (
template <>specialization): Does not participate as an independent overload candidate; it is checked only after type deduction on the Primary Template finishes. CallingStringify("hello")passes a string literal whose actual type isconst char[6]. Because the Primary Template parameter is a reference (const C&), no pointer decay occurs andCis deduced aschar[6]. The compiler only checks whether a specialization exists forchar[6]without attempting any conversion toconst char*, so Approach 1 is ignored and the Primary Template is called ("hello"). - Approach 2 (plain function overload): Participates directly in first-round overload resolution where implicit conversions and pointer decay apply.
const char[6]decays toconst char*to match Approach 2, and when a plain function ties in conversion rank (Exact Match) withStringify<char[6]>, C++ prefers the non-template function over the template, calling Approach 2 as intended ("\"hello\"").
- Approach 1 (
- Function Templates Cannot Be Partially Specialized: Customizing for pointers (
T*) or containers (std::vector<T>) requires function overloading anyway. - Overload Resolution Pitfalls (Herb Sutter’s Guideline): For the same reason as #1, explicit function template specializations do not participate directly in first-round overload resolution and are only considered after their primary template is selected, so they can be unexpectedly bypassed when mixed with other overloads such as
template <typename T> void f(T*).
- No Implicit Conversions or Pointer Decay on Template Specializations:
Practical Rule of Thumb: When Must You Use template <>?#
| Scenario | Recommended Approach | Why |
|---|---|---|
Functions where types are deduced from arguments (Stringify("hello"), compare(1, 0)) | Function Overloading | Supports implicit conversions and predictable overload resolution |
Class / Struct Templates (std::hash<T>, Type Traits) | template <> Full / Partial Specialization | Classes cannot be overloaded; specialization is the only mechanism |
Functions with identical parameter types that differ only in return type <T> (Parse<int>("8080"), Parse<double>("3.14")) | template <> Explicit Specialization | C++ forbids overloading functions that differ only by return type — plain overloads fail to compile, so template <> is required |
// When parameters are identical (std::string_view) and only the return type T differs:
// Plain overloads fail to compile, so template <> is required
template <typename T>
T Parse(std::string_view s);
template <>
int Parse<int>(std::string_view s) {
return std::stoi(std::string(s));
}
template <>
double Parse<double>(std::string_view s) {
return std::stod(std::string(s));
}
// Call site:
int port = Parse<int>("8080");
double pi = Parse<double>("3.14");