Topics / C++ for Embedded / Q8
What are templates and what is code bloat?
Short answer: Templates let you write type- or value-generic code (functions, classes) that the compiler instantiates for each set of template arguments used, producing code as efficient as hand-written specialised code. Code bloat is the downside: every distinct instantiation (e.g. RingBuffer<uint8_t, 64>, RingBuffer<uint8_t, 128>, RingBuffer<uint16_t, 64>) generates a separate copy of the functions, which can grow flash usage significantly.
#include <array>
#include <cstddef>
#include <cstdio>
template <typename T, std::size_t N>
class RingBuffer {
static_assert((N & (N - 1)) == 0, "N must be a power of two");
public:
bool push(const T &v) { if (head_ - tail_ == N) return false; buf_[head_++ & (N - 1)] = v; return true; }
bool pop(T &v) { if (head_ == tail_) return false; v = buf_[tail_++ & (N - 1)]; return true; }
std::size_t size() const { return head_ - tail_; }
private:
std::array<T, N> buf_{};
std::size_t head_ = 0, tail_ = 0;
};
int main()
{
RingBuffer<int, 4> rb;
for (int i = 0; i < 6; i++) rb.push(i);
int v;
while (rb.pop(v)) std::printf("%d ", v); // 0 1 2 3
std::printf("\n");
}
Controlling bloat
- Hoist type-independent code into a non-template base class that works on
void*and sizes, with a thin template wrapper on top (the "thin template" idiom). - Limit the number of distinct instantiations (e.g. standardise buffer sizes).
- Use
extern template/ explicit instantiation in one file to avoid duplicates across translation units (the linker removes identical duplicates anyway, but compile time shrinks). - Build with
-Os,-ffunction-sections -fdata-sections -Wl,--gc-sectionsand LTO; the linker's identical code folding (--icfin lld/gold) merges identical instantiations. - Measure: check the map file or
nm --size-sort -Cfor large template symbols.
Good embedded uses: fixed-capacity containers, register access with compile-time addresses, unit-safe types (milliseconds vs microseconds), and compile-time pin configuration.