仿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
相关推荐
Chengbei11几秒前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
eggcode1 分钟前
【Qt学习】Linux(ARM架构)在线安装Qt6.x
linux·qt·学习·arm
llz_1126 分钟前
web-第一次课后作业
java·开发语言·idea
小熊Coding17 分钟前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋921 分钟前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
xiaoshuaishuai840 分钟前
C# 内存管理与资源泄漏
开发语言·c#
lsx2024061 小时前
SVN 检出操作
开发语言
basketball6162 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
旺仔来了2 小时前
不联网的Linux下部署python环境
linux·开发语言·python
之歆3 小时前
Day16_JavaScript 轮播图与事件工程实战(下篇)
服务器·开发语言·前端·javascript·网络·性能优化