Skip to content
LeetQuant
QD03 C++ Fundamentals

QD03 · C++ Fundamentals · Lesson 5 of 6

Templates

Function and class templates, how template arguments are deduced, full and partial specialisation, why templates live in headers, and constraining templates with C++20 concepts.

16 min

Write the code once, compile it per type

The objective is to write and read simple function and class templates, predict when deduction fails, and explain where template code must live.

A template is a recipe the compiler uses to generate a separate function or class for each set of template arguments it is used with (instantiation). max_of<int> and max_of<double> are two different functions in the binary, each fully optimised for its type, with no runtime dispatch. That is the contrast with virtual functions (next lesson): templates give compile-time polymorphism.

#include <array>
#include <cstddef>
#include <iostream>
#include <string>

template <typename T>
T max_of(T a, T b) {
    return a < b ? b : a;
}

// Fixed-capacity ring buffer: T is a type parameter, N a non-type parameter.
template <typename T, std::size_t N>
class Ring {
public:
    void push(const T& x) {
        data_[head_] = x;
        head_ = (head_ + 1) % N;
        if (size_ < N) ++size_;
    }
    std::size_t size() const { return size_; }
    const T& oldest() const { return data_[(head_ + N - size_) % N]; }

private:
    std::array<T, N> data_{};
    std::size_t head_ = 0;
    std::size_t size_ = 0;
};

int main() {
    std::cout << max_of(3, 7) << ' ' << max_of(2.5, 1.5) << ' '
              << max_of<std::string>("bid", "ask") << '\n';
    std::cout << max_of<double>(1, 2.5) << '\n';  // explicit T: 1 converts to double

    Ring<int, 3> r;
    for (int px : {100, 101, 102, 103, 104}) r.push(px);
    std::cout << "size " << r.size() << ", oldest " << r.oldest() << '\n';
}
7 2.5 bid
2.5
size 3, oldest 102

The ring holds the last three of five pushes (102, 103, 104), so the oldest is 102. N is a compile-time constant, so Ring<int, 3> and Ring<int, 4> are different types and % N can be optimised. A template's body is only checked fully when it is instantiated: max_of works for any type with operator< and a copy constructor, and produces an error inside the template if called with a type that lacks one (concepts, below, move that error to the call site).

Template argument deduction

For a function template the compiler deduces T from the arguments. Each argument is deduced independently, and they must agree. Implicit conversions are not considered during deduction:

max_of(1, 2.5);  // error: no matching function for call to 'max_of'
                 // note: candidate template ignored: deduced conflicting types for parameter 'T' ('int' vs. 'double')

Fixes: specify the type (max_of<double>(1, 2.5), after which ordinary conversions apply), cast an argument, or give the template two parameters.

For a by-value parameter T x, deduction drops references and top-level const: passing a const int& deduces T = int. auto follows the same rules, which explains a common surprise:

const int ci = 5;
const int& cref = ci;
auto a = cref;         // int: a copy; reference and const dropped
const auto& b = cref;  // const int&: no copy
// std::is_same_v<decltype(a), int> and std::is_same_v<decltype(b), const int&> are both true

Class templates have their arguments written explicitly (Ring<int, 3>), although since C++17 they can be deduced from constructor arguments in simple cases (std::vector v{1, 2, 3}; deduces std::vector<int>). Forwarding references (T&& in a template) also deduce but follow special rules; they belong with move semantics in QD04.

Specialisation

A full specialisation replaces the template for one specific set of arguments. A partial specialisation replaces it for a family, such as "any pointer type". Class templates support both; function templates support only full specialisation, and in practice you overload functions instead.

#include <iostream>
#include <string>

template <typename T>
struct TypeName {
    static std::string get() { return "unknown"; }
};
template <>
struct TypeName<int> {
    static std::string get() { return "int"; }
};
template <>
struct TypeName<double> {
    static std::string get() { return "double"; }
};

// Partial specialisation: any pointer type (class templates only).
template <typename T>
struct TypeName<T*> {
    static std::string get() { return TypeName<T>::get() + "*"; }
};

int main() {
    std::cout << TypeName<int>::get() << ' ' << TypeName<double*>::get() << ' '
              << TypeName<int**>::get() << ' ' << TypeName<char>::get() << '\n';
}
int double* int** unknown

int** matches the pointer specialisation with T = int*, which matches it again with T = int, which hits the full specialisation. char has no specialisation and falls back to the primary template. The standard library uses exactly this machinery: std::hash<T> is specialised per key type (you specialise it to put your own type in an unordered_map), and std::vector<bool> is a notorious specialisation that packs bits and therefore does not return real bool& references.

Why templates live in headers

The compiler can instantiate mid<double> only in a translation unit (.cpp file plus its includes) where it can see the template's definition. Put only a declaration in the header and the definition in a .cpp, and each file compiles, but nobody generates mid<double>:

// mid.h
template <typename T>
T mid(T bid, T ask);  // declaration only

// mid.cpp
#include "mid.h"
template <typename T>
T mid(T bid, T ask) { return (bid + ask) / 2; }

// main.cpp
#include <iostream>
#include "mid.h"
int main() { std::cout << mid(100.0, 100.5) << '\n'; }
$ c++ -std=c++20 -O2 -Wall main.cpp mid.cpp -o m
Undefined symbols for architecture arm64:
  "double mid<double>(double, double)", referenced from:
      _main in main-0095fc.o
ld: symbol(s) not found for architecture arm64

main.cpp emitted a call to mid<double> expecting another file to provide it; mid.cpp saw the template but no use of it, so it generated nothing. The fix is to define templates in headers (the definition may appear in many translation units without breaking the one-definition rule). The alternative is explicit instantiation: adding template double mid<double>(double, double); to mid.cpp makes it link and print 100.25, but then only the listed types work. The cost of header-only templates is compile time and code size, since every instantiation is compiled in every file that uses it and each distinct type adds machine code.

Worked example

a constrained VWAP that works on any fill type

Write one vwap function that accepts a std::vector<EquityFill> (price as double, quantity as int) and a std::array<FuturesFill, 3> (price in integer ticks, quantity as long), and that gives a readable error when called with a container of something that is not a fill. Compute the VWAPs for equity fills 300 at 100.0 and 100 at 101.0, and futures fills 2 at 20000, 1 at 20004 and 1 at 20002.

Show solution

The template parameter is the container type, so it works for any range whose value_type has numeric price and qty members. A C++20 concept states that requirement; a requires clause applies it.

#include <array>
#include <concepts>
#include <iostream>
#include <vector>

template <typename F>
concept Fill = requires(const F& f) {
    { f.price } -> std::convertible_to<double>;
    { f.qty } -> std::convertible_to<double>;
};

template <typename Range>
    requires Fill<typename Range::value_type>
double vwap(const Range& fills) {
    double notional = 0.0, volume = 0.0;
    for (const auto& f : fills) {
        notional += f.price * f.qty;
        volume += f.qty;
    }
    return volume > 0 ? notional / volume : 0.0;
}

struct EquityFill { double price; int qty; };
struct FuturesFill { long price; long qty; };  // price in ticks

int main() {
    std::vector<EquityFill> eq{{100.0, 300}, {101.0, 100}};
    std::array<FuturesFill, 3> fut{{{20000, 2}, {20004, 1}, {20002, 1}}};
    std::cout << vwap(eq) << ' ' << vwap(fut) << '\n';
}
100.25 20001.5

By hand: equity 300×100+100×101400=40100400=100.25\frac{300 \times 100 + 100 \times 101}{400} = \frac{40100}{400} = 100.25; futures 2×20000+20004+200024=800064=20001.5\frac{2 \times 20000 + 20004 + 20002}{4} = \frac{80006}{4} = 20001.5 ticks. For the futures, f.price * f.qty is computed in long and then added to a double, so there is no truncation.

Calling vwap on a std::vector<int> now fails at the call, with the reason:

error: no matching function for call to 'vwap'
note: candidate template ignored: constraints not satisfied [with Range = std::vector<int>]
note: because 'typename vector<int>::value_type' (aka 'int') does not satisfy 'Fill'
note: because 'f.price' would be invalid: member reference base type 'const int' is not a structure or union

Without the constraint, the error would point inside the body of vwap. The standard library ships ready-made concepts in <concepts>: std::integral, std::floating_point, std::same_as, std::convertible_to, std::totally_ordered, and the shorthand template <std::integral T> constrains a parameter directly. Calling a function declared template <std::integral T> T ticks_between(T a, T b) with 1.5, 2.0 fails with "because 'double' does not satisfy 'integral'".

Knowledge check

template <typename T> T max_of(T a, T b); What happens with the call max_of(1, 2.5)?

Knowledge check

A function template is declared in a header and defined only in its own .cpp file. Another .cpp file calls it with double. What typically happens?

Knowledge check

const int ci = 5; const int& cref = ci; auto a = cref; What is the type of a?

Key takeaways

  • Templates are instantiated per set of arguments at compile time: no runtime dispatch, but more compile time and code size.
  • Deduction treats each argument separately and ignores conversions; by-value deduction and auto drop references and top-level const.
  • Class templates support full and partial specialisation; for functions, overload instead.
  • Template definitions belong in headers, because each translation unit must see the definition to instantiate it; explicit instantiation is the alternative for a fixed set of types.
  • Constrain templates with concepts (template <std::integral T>, requires) to get errors at the call site and to document requirements.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).