Templates and constexpr
Compile-time computation, type-safe registers and zero-cost abstractions.
Work done by the compiler is free
Firmware pays for every instruction in flash, cycles and energy. Anything that can be decided before the code runs, such as a baud-rate divisor, a CRC table or which pin a driver uses, should be decided by the compiler. C does this with macros. C++ does it with constexpr and templates, which are type-checked and debuggable.
constexpr
A constexpr function can run at compile time when its arguments are constants, and at run time otherwise.
constexpr uint32_t uart_brr(uint32_t clock_hz, uint32_t baud) {
return (clock_hz + baud / 2) / baud; // rounded divisor
}
static_assert(uart_brr(16'000'000, 115200) == 139);
USART2->BRR = uart_brr(16'000'000, 115200); // a constant, no division at run time
The static_assert checks the arithmetic when you build. The same calculation in C as a runnable function, which is what the compiler evaluates for you:
#include <stdio.h>
#include <stdint.h>
static uint32_t uart_brr(uint32_t clock_hz, uint32_t baud) {
return (clock_hz + baud / 2) / baud;
}
int main(void) {
uint32_t brr = uart_brr(16000000u, 115200u);
uint32_t actual = 16000000u / brr;
printf("BRR = %u, actual baud = %u, error = %d ppm\n",
brr, actual, (int)(((int64_t)actual - 115200) * 1000000 / 115200));
return 0;
}
consteval (C++20) goes further: the function must run at compile time, so an out-of-range argument becomes a build error instead of a bug.
Lookup tables built by the compiler
constexpr auto make_crc8_table() {
std::array<uint8_t, 256> t{};
for (int i = 0; i < 256; ++i) {
uint8_t c = i;
for (int b = 0; b < 8; ++b) c = (c & 0x80) ? (c << 1) ^ 0x07 : (c << 1);
t[i] = c;
}
return t;
}
constexpr auto crc8_table = make_crc8_table(); // lives in flash
No hand-pasted hex, no generator script, and the table is still in flash.
Templates
A template is a pattern the compiler stamps out for each set of arguments. Template arguments can be types or values, which is what makes them useful for hardware.
Pins known at compile time
template <uint32_t PortBase, uint8_t Pin>
struct GpioPin {
static GPIO_TypeDef *port() { return reinterpret_cast<GPIO_TypeDef *>(PortBase); }
static void set() { port()->BSRR = 1u << Pin; }
static void clear() { port()->BSRR = 1u << (Pin + 16); }
};
using StatusLed = GpioPin<GPIOA_BASE, 5>;
StatusLed::set(); // compiles to one store of a constant to a constant address
There is no object and no pointer to follow. This is as fast as a hand-written macro, but the pin number is checked and the type documents which pin a driver needs.
Fixed-capacity containers
template <typename T, size_t N>
class RingBuffer {
static_assert((N & (N - 1)) == 0, "N must be a power of two");
public:
bool push(const T &v);
bool pop(T &out);
private:
std::array<T, N> buf_{};
size_t head_ = 0, tail_ = 0;
};
RingBuffer<uint8_t, 256> uart_rx;
The size check runs at build time, and the modulo becomes a mask because N is a constant.
Type-safe units
Mixing milliseconds and microseconds, or millivolts and volts, is a classic field bug. Wrapping a number in a distinct type costs nothing and makes the mistake a compile error:
struct Millis { uint32_t v; };
struct Micros { uint32_t v; };
constexpr Micros to_us(Millis ms) { return {ms.v * 1000}; }
void delay(Micros us);
delay(to_us(Millis{50})); // fine
delay(Millis{50}); // error: no conversion from Millis to Micros
std::chrono::duration is the standard library's version of the same idea.
The cost: code size
Each distinct instantiation is a separate copy of the code. RingBuffer<uint8_t, 64> and RingBuffer<uint8_t, 128> are two classes with two push functions. Ways to keep it under control:
- Move size-independent logic into a non-template base class that takes the buffer pointer and size at run time, and keep only a thin typed wrapper in the template.
- Prefer a few standard sizes over many slightly different ones.
- Check the map file; the symbol names show every instantiation.
Pitfall: Template error messages are long because they show every layer of substitution. Read the first error, and use C++20 concepts (
template <std::integral T>) to make requirements explicit and errors short.
Interview question: How can templates make a GPIO driver both safe and as fast as macros?
Answer: Make the port and pin template parameters, such as GpioPin<GPIOA_BASE, 5>. Every operation then works on compile-time constants, so set() compiles to a single store of a constant to a constant address, with no object or pointer. Unlike a macro, the parameters are type-checked, the pin can be passed as a type to other drivers, and static_assert can reject an invalid pin number at build time.
Interview question: What is the main downside of templates in firmware and how do you manage it?
Answer: Code bloat: every distinct set of template arguments produces a separate copy of the code. Manage it by hoisting the logic that does not depend on the parameters into a non-template base class (the template becomes a thin wrapper), limiting the number of instantiations, and checking the linker map file for unexpected copies.
Going deeper
Interview question: How would you share one driver across a family of sensors with 8-, 16- and 32-bit registers?
Answer: Write the driver once as a template parameterised on the register width and the bus type, with constexpr tables for each sensor's register map, so each product gets exactly the code it needs with no run-time cost. Keep the template's interface small and its errors readable, and test each instantiation the product uses.
Interview question: What does consteval add over constexpr?
Answer: A constexpr function may run at compile time but can also run at run time if its arguments are not constants. A consteval function (C++20) must be evaluated at compile time; calling it with a run-time value is an error. That turns misuse, such as computing a baud-rate divisor that is out of range, into a build failure rather than a silent run-time result.
Interview question: How would you reduce code size when a template is instantiated for many sizes?
Answer: Move all logic that does not depend on the template parameters into a non-template base class or helper that takes the parameters (such as a buffer pointer and size) at run time, leaving only a thin, inlineable typed wrapper in the template. Limit the number of distinct instantiations by standardising sizes, and inspect the map file or nm output for duplicate instantiations.
Explain it: In your own words, explain how making a GPIO pin a template parameter makes the driver both safe and fast.
Answer: When the port address and pin number are template parameters, every operation the class performs works on compile-time constants, so setting the pin compiles to a single store of a constant to a constant address with no object or pointer to follow, as fast as a hand-written macro. Unlike a macro, the parameters are type-checked, a static_assert can reject an invalid pin number at build time, and the pin can be passed to other code as a type that documents exactly which pin it uses.