Search code examples
c++qttemplateslambdasignals-slots

A function wrapper around QObject::connect


I'm trying to write a function which passes its arguments to QObject::connect.

template <typename Func1, typename Func2>
void addConnection(const QObject* sender, Func1 signal, Func2 slot)
{
    m_connections.push_back(QObject::connect(sender, signal, slot));
}

and here is how I'm calling it:

addConnection(&m_scannerSystem, &ScannerSystem::signalStatus, [=](int status){ this->onStatusChanged(status); });

This results in an error:

'QObject::connect' : none of the 4 overloads could convert all the argument types

but I'm not able to figure out why it doesn't work.


Solution

  • You problem is that you are trying to pass a pointer to QObject but how in that case you would be able to call a member function of the other object(ScannerSysterm in your case)? The system has to know the actual type of the passed sender. So you might fix it this way:

    template <typename Sender, typename Func1, typename Func2>
    void addConnection(const Sender* sender, Func1 signal, Func2 slot)
    {
        QObject::connect(sender, signal, slot);
    }
    

    Or by using some magic Qt traits:

    template <typename Func1, typename Func2>
    void addConnection(const typename QtPrivate::FunctionPointer<Func1>::Object* sender, Func1 signal, Func2 slot)
    {
        QObject::connect(sender, signal, slot);
    }