cpp常用方法创建QObject::connection

cpp common method to create QObject::connection

我想以接受 QObject* 和接收器插槽的方式编写 ConnectMathod(...)。并建立连接

class A : public QObject {
public :
A();
~A();
signals :
void sigA(int);
slots :
void slotA(bool);
}
class B : public QObject {
public :
B();
~B();
signals :
void sigB(bool);
slots :
void slotB(int);
}

// class C : 我想写一个通用的方法,它需要接收者 (QObject*) 和插槽

class C : public QObject
{
public :
C();
~C();
signals :
void signalC(bool);

// i want help to write ConnectMathod
QMetaObject::Connection ConnectMathod(QObject* receiverObject, functionPointer)
{
QMetaObject::Connection = QObject::connect(this, &C::signalC, receiverObject, functionPointer);
return connection;
}
}

/////// main.cpp ///////

main()
{
A objA = new A();
B objB = new B();
C objC = new C();
QMetaObject::Connection connection = objC->ConnectMathod(objA, objA->slotA);
connection = objC->ConnectMathod(objB, objB->slotB);
}

ConnectMethod 设为函数模板,将任何可调用对象作为第二个参数模板参数,例如从 lambda 表达式生成的闭包:

class C : public QObject {
    Q_OBJECT
public:
C() {}
~C() {}
signals:
    void signalC(bool);
public:
    template<class Callable>
    QMetaObject::Connection ConnectMathod(QObject* contextObj, Callable cb) 
    {
        return connect(this, &C::signalC, contextObj, cb);
    }
};

A* a = new A();
B* b = new B();
C* c = new C();
c->ConnectMathod(a, [a](bool){ a->slotA(true); });
c->ConnectMathod(b, [b](bool){ b->slotB(10);});
c->signalC(true);