Back to listC++
Qt-style Signal/Slot
Lv.5769@mukitaro0 playsJan 2, 2026
Qt Signal/Slot mechanism pattern. Foundation of Qt's event system.
preview.cpp
1#include <functional>2#include <vector>3#include <string>4 5class Object {6public:7 virtual ~Object() = default;8};9 10template<typename... Args>11class Signal {12 std::vector<std::function<void(Args...)>> slots_;13 14public:15 void connect(std::function<void(Args...)> slot) {16 slots_.push_back(slot);17 }18 19 void emit(Args... args) {20 for (auto& slot : slots_) {21 slot(args...);22 }23 }24};25 26class Button : public Object {27public:28 Signal<> clicked;29 Signal<int, int> moved;30 31 void click() {32 clicked.emit();33 }34 35 void move(int x, int y) {36 moved.emit(x, y);37 }38};39 40class Label : public Object {41 std::string text_;42 43public:44 void setText(const std::string& text) {45 text_ = text;46 }47 48 void onButtonClicked() {49 setText("Clicked!");50 }51};Custom problems are not included in rankings