TL;DR
- DuckDB uses templates heavily, but the goal is usually practical.
- Database execution has many primitives with the same shape and different physical types.
- Templates let DuckDB keep the source compact while still giving the compiler direct typed code.
The database problem
Execution engines repeatedly need operations like:
- integer comparison
- decimal arithmetic
- string operations
- aggregate updates
- hash probes
- vectorized unary and binary operations
The algorithm shape is often the same. The physical type changes.
Writing every combination by hand would produce a lot of duplicated code. It would also make correctness harder, because every manual copy can drift.
What templates buy
Templates let the code express this pattern:
same algorithm shape
different physical type
different operation
The compiler can then generate specialized code for the actual type. That matters because many database primitives run in tight loops. A small abstraction cost can show up quickly.
This is why if constexpr is useful. A normal if still requires both branches to type-check. With if constexpr, the compiler can discard the branch that does not apply to the current type.
That makes one template able to cover signed and unsigned values, different aggregate states, or different vector operations without a pile of manual specializations.
What templates do not solve
Templates do not remove the need for good execution layout.
DuckDB still needs vectors, validity masks, selection vectors, string heaps, hash table payload layout, and memory accounting. Template code helps express typed operations, but it does not make a bad physical layout fast.
Templates also have costs:
- longer compile time
- larger generated code
- harder error messages
- more care needed around ABI and module boundaries
So the right use is narrow: primitives, type dispatch, and hot typed kernels where specialization matters.
Boundary
The useful framing is simple:
Templates are not the database engine.
Templates are a way to write the typed primitives inside the engine.
For DuckDB, that is a reasonable C++ tradeoff.