QtConcurrent::map and class member



  • I want to use QtConcurrent::map on a class member, but it doesn't complie. where as there is a way to use QtConcurrent::run on a class member: QtConcurrent::run(pointer, method, argument ...).
    as a workaround, I used a non-method-function that calls the method function through a static pointer (this will work only on a singlton class, which is my case).
    please advise.


  • Moderators

    Assuming MyClass::doIt() is the method you want to call, if you're on a c++11 compiler a simple lambda will do:

    void MyClass::foo() {
        QList<int> list {1,2,3,4};
        auto future = QtConcurrent::map(list, [&](int i){ doIt(i); }); //"this" captured implicitly
        future.waitForFinished();
    }
    

    If not then you can use a lambda-like local struct:

    void MyClass::foo() {
        QList<int> list; //no initializer list in c++98 :(
        list << 1 << 2 << 3 << 4;
    
        struct Lambdish {
            MyClass* m_;
            Lambdish(MyClass* m) :m_(m) {}
            void operator()(int i) { m_->doIt(i); }
        } lambdish(this);
    
        QFuture<void>future = QtConcurrent::map(list, lambdish); //no auto or lambdas in c++98 :(
        future.waitForFinished();
    }
    

    Oh, and just remember that if the parameter is anything but simple type (int, float etc.) the lambda and the lambdish operator() should take it by reference.



  • thanks Chris. this is ok. however, I just want to point out the the QtConccurent API is missing the QtConcurrent::map overload that gets a pointer and a method, like QtConcurrent::run has.


  • Moderators

    @yoavmil said:

    I just want to point out the the QtConccurent API is missing the QtConcurrent::map overload that gets a pointer and a method, like QtConcurrent::run has.

    Do you mean this?: http://doc.qt.io/qt-5/qtconcurrentmap.html#using-member-functions


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.