</>EmbeddedInterview

How do you model a hardware register in type-safe C++?

HardC++ for Embedded

Short answer: Wrap register addresses and fields in types so misuse becomes a compile error: put the address and access type (read-only, write-only, read-write) in a template, model fields with compile-time offset and width, and use enum class for field values. Everything resolves to the same single load or store as hand-written C (*(volatile uint32_t*)addr), but writing to a read-only register or putting a value in the wrong field no longer compiles.

#include <cstdint>
#include <cstdio>

enum class Access { RO, WO, RW };

template <uintptr_t Addr, Access A = Access::RW>
struct Reg {
    static volatile uint32_t &ref() { return *reinterpret_cast<volatile uint32_t *>(Addr); }
    static uint32_t read() { static_assert(A != Access::WO, "write-only register"); return ref(); }
    static void write(uint32_t v) { static_assert(A != Access::RO, "read-only register"); ref() = v; }
};

template <typename R, unsigned Offset, unsigned Width>
struct Field {
    static constexpr uint32_t mask = ((1u << Width) - 1u) << Offset;
    static void set(uint32_t v) {
        uint32_t r = R::read();
        R::write((r & ~mask) | ((v << Offset) & mask));
    }
    static uint32_t get() { return (R::read() & mask) >> Offset; }
};

enum class Mode : uint32_t { Input = 0, Output = 1, Alt = 2, Analog = 3 };

// demo: point the "register" at RAM so this runs on a PC
static uint32_t fake_moder;
using GPIOA_MODER = Reg<0>;                       // placeholder; real code uses 0x4002'0000
struct Moder {                                    // adapter so the demo can use fake memory
    static uint32_t read() { return fake_moder; }
    static void write(uint32_t v) { fake_moder = v; }
};
template <unsigned Pin> using PinMode = Field<Moder, Pin * 2, 2>;

int main()
{
    PinMode<5>::set(static_cast<uint32_t>(Mode::Output));
    PinMode<6>::set(static_cast<uint32_t>(Mode::Alt));
    std::printf("MODER=0x%08X pin5=%u\n", (unsigned)fake_moder, (unsigned)PinMode<5>::get());   // 0x00002400 1
    (void)sizeof(GPIOA_MODER);
}

Real-world options

  • Vendor CMSIS headers (C structs with volatile members) are the baseline; C++ wrappers sit on top.
  • Libraries: Kvasir, modm (generated from vendor data), cpp-register styles, Rust's svd2rust as the inspiration; SVD files describe registers and fields so code can be generated.
  • reinterpret_cast makes these functions non-constexpr; keep addresses as uintptr_t template parameters and cast only inside the access function.

Benefits to mention: read-only/write-only enforcement, field width checks, impossible to mix up registers of different peripherals, self-documenting code, and zero overhead (check the disassembly).