Variant Command Dispatcher

Hard C++ Abstraction Asked at Google
Solve this problem

Build a command dispatcher over std::variant so adding a new command type is a compile error until every handler is updated, rather than a silent runtime fallthrough.

Constraints

  • Commands: SetGain{int}, Reset{}, Calibrate{float}.
  • Dispatch via std::visit with an overload set.
  • Adding a fourth alternative must fail to compile until handled.
  • No dynamic_cast, no virtual dispatch.
  • Handler returns an int status code.
Starter codeC++
1#include <variant>2 3struct SetGain { int value; };4struct Reset {};5struct Calibrate { float target; };6 7using Command = std::variant<SetGain, Reset, Calibrate>;8 9int dispatch(const Command& cmd);