闲来无事,模仿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 <<