The Analogy: The Pastry Cutter
A pastry cutter is not a biscuit. It is the shape a biscuit will take, and it works the same whether you press it into shortbread, gingerbread or scone dough. One tool, one shape, many materials.
A template is that cutter. You write the shape of a function or class once, leaving the type as a blank, and the compiler stamps out a real function or class for every type you actually use. The stamped-out versions are ordinary code — fully type-checked, fully optimised, no runtime cost whatsoever. That last point is what separates C++ templates from generics in most other languages: nothing is decided at runtime, because by the time the program runs, the specific versions already exist.
The price is that errors arrive at the stamping stage, which historically meant unreadable messages. Concepts, added in C++20, largely fix that.
Syntax or Core Structure
#include <iostream>
#include <string>
#include <vector>
// --- A function template. 'T' is a placeholder for a type.
template <typename T>
T larger(T a, T b) {
return (a > b) ? a : b;
}
// --- Several parameters, and a deduced return type.
template <typename A, typename B>
auto add(A a, B b) {
return a + b; // return type deduced from A + B
}
// --- A non-type template parameter: a compile-time value, not a type.
template <typename T, std::size_t N>
T sumOf(const T (&data)[N]) {
T total{}; // value-initialised: 0 for numbers
for (const T& x : data) { total += x; }
return total;
}
// --- A class template.
template <typename T>
class Stack {
std::vector<T> items;
public:
void push(const T& value) { items.push_back(value); }
bool pop(T& out) {
if (items.empty()) { return false; }
out = items.back();
items.pop_back();
return true;
}
bool empty() const { return items.empty(); }
std::size_t size() const { return items.size(); }
};
int main() {
std::cout << larger(3, 9) << "\n"; // T = int
std::cout << larger(2.5, 1.5) << "\n"; // T = double
std::cout << larger<std::string>("apple", "pear") << "\n"; // T given explicitly
std::cout << add(2, 3.5) << "\n"; // 5.5
int nums[4]{1, 2, 3, 4};
std::cout << sumOf(nums) << "\n"; // 10, N deduced as 4
Stack<std::string> words; // must name the type
words.push("hello");
words.push("world");
std::string top;
words.pop(top);
std::cout << top << " " << words.size() << "\n"; // world 1
return 0;
}
Function templates usually deduce their types from the arguments. Class templates before C++17 always needed them spelled out; since C++17, std::vector v{1, 2, 3}; deduces too.
Technical Depth: Instantiation and Its Consequences
A template is not code until it is used
template <typename T>
void show(T value) { std::cout << value; }
That produces no machine code at all. Call show(42) and the compiler generates show<int>; call show(2.5) and it generates show<double> as well. Never call it and nothing is emitted — which is why an unused template can contain code that would not compile for some types.
The consequence: template definitions must be visible where they are used, so they live in headers. Splitting one across a .h and a .cpp produces "undefined reference" at link time, because the .cpp was never told which types to stamp out.
Templates versus other approaches
| Templates | Virtual functions | void* / macros | |
|---|---|---|---|
| Type checked | Fully | Fully | Barely |
| Dispatch decided | Compile time | Run time | N/A |
| Runtime cost | None | Vtable indirection | Casting, no safety |
| Code size | One copy per type | One copy total | One copy |
| Types must be known | At compile time | No, open set | No |
Templates and virtual functions solve different problems: templates when the types are fixed at compile time, virtuals when they vary at runtime.
Overload resolution prefers a non-template
An exact non-template match always beats a template. That is how you special-case one type:
template <typename T>
void describe(T value) { std::cout << "generic: " << value << "\n"; }
void describe(bool b) { std::cout << "flag: " << (b ? "on" : "off") << "\n"; }
describe(42); // generic: 42
describe(true); // flag: on -- the non-template wins
Full specialisation
For a class template, you can supply an entirely different implementation for one type:
template <typename T>
class Formatter {
public:
std::string format(const T& value) const { return std::to_string(value); }
};
template <> // full specialisation
class Formatter<bool> {
public:
std::string format(const bool& value) const { return value ? "yes" : "no"; }
};
Formatter<int>{}.format(42); // "42"
Formatter<bool>{}.format(true); // "yes"
Type deduction strips references and const
template <typename T> void byValue(T x); // T deduced as int for a const int&
template <typename T> void byRef(const T& x); // no copy -- prefer this
template <typename T> void f(T x) copies its argument, which for a large container is exactly the cost you were trying to avoid. Take const T& unless you specifically want the copy.
Variadic templates
template <typename... Args>
void logAll(const Args&... args) {
(std::cout << ... << args) << "\n"; // C++17 fold expression
}
logAll("x=", 42, " y=", 3.5); // x=42 y=3.5
typename... Args accepts any number of types. This is how std::make_unique and printf-style logging are written without macros.
Constraining templates: concepts (C++20)
Unconstrained templates accept anything and fail deep inside the body with a wall of errors. A concept moves the error to the call site:
#include <concepts>
template <typename T>
requires std::totally_ordered<T>
T larger(T a, T b) { return (a > b) ? a : b; }
// Shorthand form:
template <std::integral T>
T halve(T n) { return n / 2; }
halve(7); // fine
// halve(7.5); // error at the CALL SITE: double is not integral
Before C++20 the equivalent was static_assert inside the body:
template <typename T>
T halve(T n) {
static_assert(std::is_integral<T>::value, "halve requires an integer type");
return n / 2;
}
if constexpr picks a branch at compile time
template <typename T>
std::string describe(const T& value) {
if constexpr (std::is_integral_v<T>) {
return "integer " + std::to_string(value);
} else if constexpr (std::is_floating_point_v<T>) {
return "real " + std::to_string(value);
} else {
return "something else";
}
}
The discarded branches are not compiled at all, so each may contain code that would be invalid for the other types.
Costs to be aware of
Every distinct type instantiates a fresh copy, so a template used with twelve types produces twelve functions — good for speed, bad for binary size and compile time. Heavy template use is the main reason large C++ projects build slowly. Keep templates thin: put the type-dependent part in the template and factor shared logic into an ordinary non-template function it calls.
Real World Example: A Generic Result Cache
A cache is the classic template use case: the storing, looking up, evicting logic is identical whatever you cache, but the key and value types differ at every call site. Writing it once as a template gives you a typed cache for strings, for structs, for anything — with no runtime cost and no casting.
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <vector>
template <typename Key, typename Value>
class Cache {
public:
explicit Cache(std::size_t capacity) : limit(capacity) {}
void put(const Key& key, const Value& value) {
if (entries.find(key) == entries.end() && entries.size() >= limit) {
evictOldest();
}
entries[key] = value;
order.push_back(key);
}
std::optional<Value> get(const Key& key) const {
++lookups;
auto it = entries.find(key);
if (it == entries.end()) return std::nullopt;
++hits;
return it->second;
}
std::size_t size() const { return entries.size(); }
std::size_t hitCount() const { return hits; }
std::size_t lookupCount() const { return lookups; }
private:
void evictOldest() {
if (order.empty()) return;
entries.erase(order.front());
order.erase(order.begin());
}
std::size_t limit;
std::map<Key, Value> entries;
std::vector<Key> order;
mutable std::size_t hits = 0;
mutable std::size_t lookups = 0;
};
// A free function template that works with ANY cache instantiation.
template <typename C>
void report(const std::string& label, const C& cache) {
std::cout << label << ": " << cache.size() << " entries, "
<< cache.hitCount() << "/" << cache.lookupCount() << " hits\n";
}
struct User {
std::string name;
int age = 0;
};
int main() {
Cache<std::string, double> prices(3);
prices.put("widget", 4.99);
prices.put("gasket", 1.25);
prices.put("flange", 8.50);
if (auto p = prices.get("gasket")) {
std::cout << "gasket costs " << *p << "\n";
}
prices.get("missing"); // a miss
prices.put("bolt", 0.35); // evicts "widget"
std::cout << "widget present? "
<< (prices.get("widget").has_value() ? "yes" : "no") << "\n";
Cache<int, User> users(10); // same template, unrelated types
users.put(1, User{"Ada", 36});
users.put(2, User{"Grace", 45});
if (auto u = users.get(2)) {
std::cout << "user 2 is " << u->name << ", age " << u->age << "\n";
}
report("prices", prices);
report("users", users);
}
Output:
gasket costs 1.25
widget present? no
user 2 is Grace, age 45
prices: 3 entries, 2/4 hits
users: 10 entries...
Several decisions in that code are worth spelling out. Cache takes two type parameters because a cache's key and value vary independently — one parameter would have forced them to be the same type. get returns std::optional<Value> rather than Value because "not found" is a normal outcome, not an error, and there is no sensible sentinel that works for every possible Value; a Value template parameter could be double, a struct, or std::string, so -1 or "" would each be wrong for something. hits and lookups are mutable so that get can stay const — reading the cache does not logically modify it even though it does bump a counter. The eviction logic lives in a private evictOldest because put should read as a policy statement, not a bookkeeping routine. And report is a function template taking const C&: it never names Key or Value, so it works with Cache<std::string, double> and Cache<int, User> alike, needing only that whatever it is handed has size(), hitCount() and lookupCount(). That is duck typing checked at compile time — no base class, no virtual functions, no indirection.
The compiler stamps out two entirely separate classes here. Cache<std::string, double> and Cache<int, User> share a name in your source and nothing at all in the binary; each gets its own put, its own get, its own std::map specialisation. Both are as fast as if you had hand-written them.
Common Mistakes
- Putting template definitions in a
.cppfile. You get "undefined reference" at link time. Template definitions belong in headers. - Taking parameters by value.
template <typename T> void f(T x)copies. Useconst T&for anything larger than a couple of machine words. - Expecting errors at the definition. A template with a mistake in it compiles fine until something instantiates it. Test every template with at least one type.
- Reading instantiation errors from the top. The useful line is usually near the bottom, where the actual type mismatch is reported. Or add a concept and get one clear error instead.
- Forgetting
typenamefor dependent types. Inside a template,typename T::value_type x;needs the keyword;T::value_type x;is a parse error because the compiler cannot know it is a type. - Assuming the type supports what you use. If your template body writes
a > b, every type it is instantiated with must haveoperator>. Constrain it or document it. - Uninitialised accumulators.
T total;leaves adoublefull of garbage. WriteT total{};for value initialisation. - Over-templating. If a function only ever handles
std::string, making it a template adds compile time and error-message noise for nothing.
Best Practices
- Deduce, don't spell out. Write
larger(a, b), notlarger<int>(a, b), unless you need to force a conversion. - Constrain your templates. Use C++20 concepts where available,
static_assertwith type traits otherwise. It turns a hundred-line error into one line. - Take
const T&, return by value. The standard convention, and correct in the overwhelming majority of cases. - Value-initialise with
{}.T x{};is zero for arithmetic types and default-constructed for classes. - Keep the type-dependent part small. Factor the shared logic into a non-template helper so only the thin wrapper multiplies across types.
- Prefer standard-library templates.
std::vector,std::map,std::optionaland the<algorithm>functions already cover most needs. - Use
if constexprover specialisation for simple type-based branching. It is far easier to read. - Name parameters meaningfully.
typename Key, typename Valuebeatstypename T, typename U.
Practice Exercises
- Write a function template
template <typename T> T clamp(T value, T low, T high)that returnslowifvalueis below it,highif above, andvalueotherwise. Test it withintanddouble. - Write a class template
Pair<A, B>storing two values, withfirst(),second(), and aswapped()method returning aPair<B, A>. Test it withPair<std::string, int>. - Write
template <typename T> std::optional<std::size_t> indexOf(const std::vector<T>& items, const T& target)returning the position of the first match orstd::nullopt. - Write a variadic template
template <typename... Args> std::size_t countArgs(const Args&... args)returning how many arguments it received, and asumAllthat adds them with a fold expression. Explain whycountArgs()with no arguments returns 0.