is it possible to use QtConcurrent::run() with a function member of a class

孤街浪徒 提交于 2019-11-28 20:37:57
Kyle Lutz

Yes, this is possible (and quite easy).

Here is an example (from the Qt documentation):

// call 'QStringList QString::split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const' in a separate thread
QString string = ...;
QFuture<QStringList> future = QtConcurrent::run(string, &QString::split, QString(", "), QString::KeepEmptyParts, Qt::CaseSensitive);
...
QStringList result = future.result();

Basically, all you have to do is pass a pointer to the object as the first argument and the address of the method as the second argument (followed by any other arguments).

See: https://doc.qt.io/qt-5/qtconcurrentrun.html

The problem is that when you use a pointer to member function, you need to somehow provide the this parameter also (i.e., the object on which the member function should be called).

The syntax for this is quite difficult if you haven't used it before. It might be good to read http://www.parashift.com/c++-faq-lite/pointers-to-members.html .

Say you have a class Dog and a function Dog::walkTheDog(int howlong_minutes). Then you ought to be able to use std::bind1st and std::mem_fun to make it suitable for QtConcurrent::run:

Dog dog;
// Walk this dog for 30 minutes
QtConcurrent::run(std::bind1st(std::mem_fun(&Dog::walkTheDog), &dog), 30);

std::bind1st(std::mem_fun(&Dog::walkTheDog), &dog) returns a function-like object which has bound the member function to a particular dog. From that point you can use it much like you could use a standalone function.

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