Search code examples
c++qtqobject

cpp common method to create QObject::connection


i want to write ConnectMathod(...) in such way that it accept QObject* and receiver slot. and establish connection

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 : i want to write common mathod which expect receiver (QObject*) and slot

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);
}


Solution

  • Make ConnectMethod as a function template which takes as second argument template parameter which will be any callable object, for example a closure generated from lambda expression:

    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);