Observer Pattern for Sensor Events

Medium C++ Architecture Asked at Bosch
Solve this problem

Implement a compile-time-bounded observer registry so sensor drivers can notify several consumers without dynamic allocation.

Constraints

  • Maximum 4 observers, fixed at compile time.
  • `subscribe` returns false when full rather than throwing.
  • Notification must be safe if an observer unsubscribes during the callback.
  • No std::vector, no new/delete.
  • Observers are plain function pointers with a void* context.
Starter codeC++
1#include <cstddef>2 3class SensorTopic {4public:5    using Callback = void (*)(void* ctx, int value);6    bool subscribe(Callback cb, void* ctx);7    void unsubscribe(Callback cb, void* ctx);8    void publish(int value);9};