Connecting C++11 lambdas to Qt4 Signals with libffi (now portable)

I know that this is probably not very useful, considering that it’s not portable and with Qt5 about to be released in June, but I found it interesting to experiment with the new language features and libffi.

The result is a class which lets you connect any function pointer or lambda, with or without bound variables, to Qt4 signals. Example of what you can do with it:

#include <QtCore>
#include <QtGui>
#include <QtDebug>

#include "lambdaconnection.h"

void printValue(int i) {
    qDebug() << "value:" << i;
}

int main(int argc, char **argv) {
    QApplication app(argc, argv);

    QSlider slider(Qt::Horizontal);
    slider.show();

    LambdaConnection::connect(&slider, SIGNAL(valueChanged(int)), &printValue);

    LambdaConnection::connect(&slider, SIGNAL(valueChanged(int)), [&app] (int i)
    {
        if (i >= 99) {
            qDebug() << "quit.";
            app.quit();
        }
    }); 

    app.exec();
}

Quite nice, I think :) You can get the source for lambdaconnection.h here.

Its main drawback is the use of pointers to member functions as ordinary function pointers. It works with gcc and maybe clang, but it’s probably going to break with other compilers and/or operating systems. UPDATE: By converting everything to std::function, we can have one template function which is called by libffi and handles any further lambda calls. No need for member-function-pointers anymore. Portability shouldn’t be an issue anymore, too.

Additionally, to avoid code duplication, it simply converts function pointers to std::function objects. This adds some overhead when calling the function pointer.

Anyway, it’s only an afternoon’s work and it was fun to code. Maybe someone will find this interesting :)

2 thoughts on “Connecting C++11 lambdas to Qt4 Signals with libffi (now portable)

  1. Ivan

    Heh, love playing with C++0x as well.

    As for std::function, don’t sweat about it, the overhead shouldn’t be much. Guessing, well less than the overhead of Qt’s meta-object system itself.

    Cheerio!

Comments are closed.