Important: Please read the Qt Code of Conduct -

Who's interested in template QObjects?

  • Moderators

    Hi all,

    Currently, template classes cannot be QObjects; one of C++'s powerful features cannot be used on QObjects.

    There has been some work done to change this. It wasn't obvious if the benefits outweighed the potential issues or not, and the efforts were put off to another day:

    I'm interested to see this feature implemented. Does anyone have any cool ideas on how template QObjects could be used?

    Here's one I thought might be handy: The ability to run an arbitrary function in a separate thread, and have the return value delivered straight into a slot -- much cleaner than QtConcurrent::run()

    // Template definition
    template <typename T>
    QParallel : public QObject {

    static QParallel* run(T (function)(), bool autoDelete = true) {

    Starts running the function in a separate thread, then returns a
    pointer to let the user connect the finished() signal to their slot(s).

        The user doesn't need to delete the object manually.

    void finished(T);

    // Expensive function
    QString myExpensiveFunc();

    // User code
    auto p = QParallel<QString>::run(&myExpensiveFunc);
    connect(p, SIGNAL(finished(QString)),
    this, SLOT(processResult(QString)));

    (This example doesn't take parameters for myExpensiveFunc(), but those can easily be supported via C++11's variadic templates)

  • I do not have a cool idea for where to have templated QObject.
    However in some case it would be convenient to use a template with QObject.

    As you pointed already out the current implementations are simply cutting off one of C++ powerful possibilities. Certainly there are always ways around it, but very soon you find yourself copy and pasting code and changing the class names.

  • Moderators

    [quote author="koahnig" date="1390484857"]very soon you find yourself copy and pasting code and changing the class names. [/quote]Precisely! Keeping them in sync with each other is not a pleasant task, either.

Log in to reply