仿QT信号与槽的简易框架

  • 信号与槽通常被用于对象间的通信、事件驱动等场景,相比于回调函数的优势是动态连接、支持多对多、参数类型检查更安全、更加松耦合等。

  • 这里提供一个C++实现的简易仿信号与槽的框架。注:QT中信号与槽是基于较复杂的元对象系统,而这里只是以基本功能为导向提供简易实现。

    信号和槽函数的创建、连接、触发、断连。

  • code

cpp 复制代码
#include <iostream>
#include <functional>
#include <vector>
#include <map>

#define CONNECT(signal, slot) signal.connect(slot, #slot)
#define DISCONNECT(signal, slot) signal.disconnect(#slot)

template <typename... Args>
class GenericSignal
{
public:
    using SlotType = std::function<void(Args...)>;

    void connect(SlotType slot, const std::string &slotName)
    {
        slots[slotName] = std::move(slot);
    }

    void disconnect(const std::string &slotName)
    {
        auto it = slots.find(slotName);
        if (it != slots.end())
        {
            slots.erase(it);
        }
    }

    template <typename... SignalArgs>
    void emitSignal(SignalArgs &&...args) const
    {
        for (const auto &slotPair : slots)
        {
            slotPair.second(std::forward<SignalArgs>(args)...);
        }
    }

private:
    std::map<std::string, SlotType> slots;
};

void slotFunction1(int arg1, const std::string &arg2)
{
    std::cout << "Slot 1 called with " << arg1 << " and " << arg2 << std::endl;
}

void slotFunction2(int arg1, const std::string &arg2)
{
    std::cout << "Slot 2 called with " << arg1 << " and " << arg2 << std::endl;
}

int main()
{
    GenericSignal<int, const std::string &> signal;

    CONNECT(signal, &slotFunction1);
    CONNECT(signal, &slotFunction2);

    std::cout << "Emitting signal..." << std::endl;
    signal.emitSignal(1, "Hello");

    DISCONNECT(signal, &slotFunction1);

    std::cout << "\nEmitting signal after disconnecting slotFunction1..." << std::endl;
    signal.emitSignal(2, "Hello");

    return 0;
}
  • result
bash 复制代码
Emitting signal...
Slot 1 called with 1 and Hello
Slot 2 called with 1 and Hello

Emitting signal after disconnecting slotFunction1...
Slot 2 called with 2 and Hello
相关推荐
星晨雪海1 小时前
企业标准 DTO 传参 + Controller + Service + 拷贝工具类完整版
java·开发语言·python
龙侠九重天1 小时前
C# 机器学习数据处理
开发语言·人工智能·机器学习·ai·c#
IT 行者6 小时前
Web逆向工程AI工具:JSHook MCP,80+专业工具让Claude变JS逆向大师
开发语言·javascript·ecmascript·逆向
程序员 沐阳8 小时前
JavaScript 内存与引用:深究深浅拷贝、垃圾回收与 WeakMap/WeakSet
开发语言·javascript·ecmascript
Mr_Xuhhh9 小时前
Java泛型进阶:从基础到高级特性完全指南
开发语言·windows·python
He1955019 小时前
wordpress搭建块
开发语言·wordpress·古腾堡·wordpress块
老天文学家了9 小时前
蓝桥杯备战Python
开发语言·python
赫瑞9 小时前
数据结构中的排列组合 —— Java实现
java·开发语言·数据结构
初夏睡觉10 小时前
c++1.3(变量与常量,简单数学运算详解),草稿公放
开发语言·c++
升职佳兴10 小时前
C盘爆满自救:3步无损迁移应用数据到E盘(含回滚)
c语言·开发语言