仿QT信号与槽的简易框架

本文讲解了C++中的信号与槽机制,包括其在对象间通信的应用、优势以及一个简单的实现,涉及信号的连接、断开和触发操作。
摘要由CSDN通过智能技术生成
  • 信号与槽通常被用于对象间的通信、事件驱动等场景,相比于回调函数的优势是动态连接、支持多对多、参数类型检查更安全、更加松耦合等。

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

  • code

#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
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
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值