仿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
相关推荐
兔兔兔兔18 分钟前
记录C++ 8
开发语言·c++
名字还没想好☜43 分钟前
Go 1.23 range-over-func 迭代器实战:自定义可迭代类型、提前退出与惰性求值
开发语言·后端·golang·go·迭代器
脑子不好的小菜鸟1 小时前
秋招、实习 小知识点复习 (C/C++/Linux)—— 碎片时间可看
c++·求职招聘
喵同志不止步于码农1 小时前
Java Caffeine 快速入门
java·开发语言·后端·并发·缓存一致性
2kπ1 小时前
QT开发笔记
开发语言·笔记·qt
青 春 记 忆1 小时前
零基础入门Python15|关联、聚合、索引与事务:订单数据库
开发语言·python·后端开发
江屿风2 小时前
【STM32基础篇】【嵌入式生态问题及历史追溯】流食般投喂
大数据·开发语言·人工智能·笔记·stm32·嵌入式硬件
charlie1145141912 小时前
深探std::vector:三指针、扩容与迭代器失效
开发语言·c++·开源项目
laplaya2 小时前
ROS常用消息之PointCloud2
c++
asyxchenchong8882 小时前
R语言混合效应(多水平/层次/嵌套)模型及贝叶斯实现技术应用
开发语言·r语言