QtConcurrent::map() with member function = can not compile

后端 未结 1 636
忘掉有多难
忘掉有多难 2021-01-07 05:42

My project is to create a small program which demonstrates the work of a search engine: indexing and returning result for arbitrary queries. I\'ve done the work with the ind

相关标签:
1条回答
  • 2021-01-07 05:55

    To be able to call a pointer-to-member, you need, in addition to that functions formal arguments, an instance of that class (the this pointer that you get inside member functions).

    There are two ways to handle this: create a simple functor to wrap the call, or use a lambda.

    The functor would look like this:

    struct AddWrapper {
      MainWindow *instance;
      AddWrapper(MainWindow *w): instance(w) {}
      void operator()(QString const& data) {
        instance->add(data);
      }
    };
    

    And you'd use it like:

    AddWrapper wrap(this);
    QtConcurrent::map(list, wrap);
    

    (Careful with the lifetime of that wrapper though. You could make that more generic - you could also store a pointer-to-member in the wrapper for instance, and/or make it a template if you want to reuse that structure for other types.)

    If you have a C++11 compiler with lambdas, you can avoid all that boilerpalte:

    QtConcurrent::map(list, [this] (QString const& data) { add(data); });
    

    Note: I'm not sure how QtConcurrent::MemberFunctionWrapper1 got involved in your example, I'm not seeing it here. So there might be a generic wrapper already in Qt for this situation, but I'm not aware of it.

    0 讨论(0)
提交回复
热议问题