信号槽原理

本文探讨了QT信号槽的原理,并分享了一段模仿QT信号槽机制的代码实现。作者在实践中遇到多参数信号槽的挑战,指出要达到QT的简洁性需要元编译机制。同时,文中讨论了静态成员函数作为槽函数的局限性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

闲来无事,模仿QT的信号槽函数写了一段代码:

#include <iostream>


using namespace std;
typedef void (*slotType)(void);

#define emit

class A
{
public:
    A(){slot = NULL;}
    static void Clicked(void)
    {
	slotType pFunc = NULL;
	pFunc = (slotType )slot;
	if(pFunc) pFunc();
    };

    static void (* slot);
};
void* A::slot = NULL;
class B
{
public:
    B(){}
    static void slotOnClick(void)
    {
	cout << "test slotOnClick()" << endl;
    }
    
};

template<class S, class R, typename slotFuncType>
int connect(S* sender, slotFuncType signal, R* receiver, slotFuncType slot)
{
    int ret = 0;
    if( slot )
    {
	sender->slot = (void*)slot;
	ret = 1;
    }
    return ret;
}

int main(int argc, char *argv[])
{
    cout << "Hello world in C++." << endl;
    A a;
    B b;
    emit A::Clicked();
    connect(&a, A::Clicked, &b, B::slotOnClick);
    emit A::Clicked();
    
    return 0;
}

哈哈,尝试了一下,想要进行多参数的信号槽进行关联就不太好实现了,如果要做到和QT一样简洁就必须用到元编译机制了

#include <iostream>


using namespace std;
typedef void (*slotType)(...);

#define emit
#define SIGNAL_DEFINE(signalFunc) \
static void signalFunc{\
    slotType pFunc = NULL;\
    pFunc = (slotType )slot;\
    if(pFunc) pFunc();\
}
#define SIGNAL_BEGIN(funcName) static void funcName 
 



class A
{
public:
    A(){slot = NULL;}
    /*
    static void Clicked(void)
    {
	slotType pFunc = NULL;
	pFunc = (slotType )slot;
	if(pFunc) pFunc();
    };
    */
    SIGNAL_DEFINE(Clicked(void));
    SIGNAL_BEGIN(Notify(int x));

    

    static void (* slot);
};
void* A::slot = NULL;
void A::Notify(int x)
{
    slotType pFunc = NULL;
    pFunc = (slotType )slot;
    if(pFunc) pFunc(x);
}


class B
{
public:
    B(){}
    static void slotOnClick(void)
    {
	cout << "test slotOnClick()" << endl;
    }

    static void slotNotify(int x)
    {
	cout << "get the Notify value:" << x <<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值