</>EmbeddedInterview

What is CRTP and how does static polymorphism compare with virtual functions?

HardC++ for Embedded

Short answer: The Curiously Recurring Template Pattern (CRTP) is a class that derives from a template instantiated with itself: class Uart1 : public UartBase<Uart1>. The base can call derived-class functions through static_cast<Derived*>(this), which the compiler resolves at compile time, so there is no vtable, no vptr and calls can be inlined. It gives a common interface and shared code with zero run-time cost, but you lose the ability to store different types behind one base pointer at run time.

#include <cstdint>
#include <cstdio>

template <typename Derived>
class UartBase {
public:
    void write(const char *s) {                    // shared code, written once
        while (*s) static_cast<Derived *>(this)->put(static_cast<uint8_t>(*s++));
    }
};

class Uart1 : public UartBase<Uart1> {
public:
    void put(uint8_t c) { std::putchar(c); }       // would write the UART1 data register
};

class LogBuffer : public UartBase<LogBuffer> {
public:
    void put(uint8_t c) { if (n < sizeof buf) buf[n++] = c; }
    uint8_t buf[64]; unsigned n = 0;
};

template <typename Port>
void banner(UartBase<Port> &p) { p.write("boot ok\n"); }    // generic, no virtual calls

int main()
{
    Uart1 u; LogBuffer lb;
    banner(u); banner(lb);
    std::printf("log has %u bytes\n", lb.n);                  // log has 8 bytes
}
Virtual functions CRTP / templates
Dispatch run time (indirect call) compile time (direct, inlinable)
RAM per object vptr none
Flash one vtable per class; one copy of generic code one copy of generic code per type (possible bloat)
Heterogeneous containers (Sensor* list of mixed types) yes no (unless combined with a small virtual wrapper)
Error messages simple template errors can be verbose (C++20 concepts help)

When to use which: CRTP/templates when the configuration is fixed at compile time (which UART, which pins, which buffer size); virtual interfaces when types are chosen at run time (plugin-style sensor drivers, mocks in tests, different boards from one binary). C++20 concepts document and check the required interface (requires { p.put(uint8_t{}); }).