EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 37
Embedded C++: Templates and constexpr
Compile-time work, zero run-time cost.
A template builds code for many types from one definition. A fixed-size buffer class can take its length as a template parameter, so memory is sized at compile time.
constexpr lets the compiler compute values such as tables or baud-rate divisors during the build. The chip just reads the finished result.
Both features avoid dynamic memory, which is ideal for small devices.
EXAMPLE
template <typename T, unsigned N>
class Buffer {
public:
void put(T v) { data[idx++ % N] = v; }
private:
T data[N]; unsigned idx = 0;
};
constexpr unsigned divisor(unsigned clk, unsigned baud) { return clk / (16 * baud); }
Buffer<unsigned char, 32> rx;