C++ Templates & STL

Templates & Generic Code

Templates are how C++ writes code that works for any type with zero runtime cost — the mechanism the entire STL is built on. The compiler stamps out a specialized version for each type you use.

C++20 3 Topics
01

Function Templates

A function template is a recipe. Write it once with a type parameter T, and the compiler generates a concrete function for each type you call it with — all resolved at compile time, so there's no runtime overhead.

C++ — Function Template
template<typename T>
T maximum(T a, T b) {
    return a > b ? a : b;
}

maximum(3, 7);          // 7   — T deduced as int
maximum(2.5, 1.5);      // 2.5 — T deduced as double
maximum<std::string>("a", "b");   // "b" — explicit type

// works for ANY type that supports > — one function, all types
Templates give you generic code with zero abstraction cost. Unlike Java generics (which erase to Object) or virtual dispatch, each instantiation is fully specialized and inlined — as fast as if you'd hand-written it for that type.
02

Class Templates

The same idea applies to classes. std::vector<T>, std::map<K,V> — every STL container is a class template. Here's a minimal one of your own.

C++ — Class Template
template<typename T>
class Box {
    T value;
public:
    Box(T v) : value(v) {}   // member initializer list
    T get() const { return value; }
    void set(T v) { value = v; }
};

Box<int> a(42);
a.get();           // 42

Box<std::string> b("hi");
b.get();           // "hi" — same class, different type
03

STL Algorithms

The <algorithm> header is a toolbox of template functions that work on any container through iterators. Prefer them over hand-written loops — they're correct, optimized, and express intent clearly.

C++ — <algorithm>
#include <algorithm>
#include <numeric>

std::vector<int> v = {5, 2, 8, 1, 9, 3};

std::sort(v.begin(), v.end());          // [1,2,3,5,8,9]
std::reverse(v.begin(), v.end());       // [9,8,5,3,2,1]

auto it = std::find(v.begin(), v.end(), 8);   // iterator to 8
int big = std::count_if(v.begin(), v.end(),
    [](int x){ return x > 4; });          // 3

int sum = std::accumulate(v.begin(), v.end(), 0);   // 28
int mx  = *std::max_element(v.begin(), v.end());     // 9
AlgorithmDoes
sortSorts a range in place
find / find_ifLocates a value or first match
count_ifCounts elements matching a predicate
accumulateFolds a range to one value (sum, product)
transformApplies a function to each element
max_element / min_elementIterator to the largest / smallest

Quick Quiz

1. C++ templates are resolved at…
2. Compared to Java generics, C++ templates…
3. std::vector<T> is an example of a…
4. std::accumulate(v.begin(), v.end(), 0) computes…
5. STL algorithms operate on containers through…