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

两盒软妹~` 提交于 2019-12-01 01:18:42

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!