C++ 是否可以将 QtConcurrent::run() 与类的函数成员一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2152355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is it possible to use QtConcurrent::run() with a function member of a class
提问by yan bellavance
I can't seem to be able to associate QtConcurrent::run()
with a method (function member of a class) only with a simple function. How can I do this?
我似乎无法QtConcurrent::run()
仅将一个简单的函数与方法(类的函数成员)相关联。我怎样才能做到这一点?
With a regular function I cannot emit signals and its a drag. Why would anyone find this a better alternative to QThread
is beyond me and would like some input.
使用常规功能,我无法发出信号,而且很拖累。为什么有人会发现这是一个更好的替代方案,QThread
这超出了我的理解,并希望得到一些意见。
回答by Kyle Lutz
Yes, this is possible (and quite easy).
是的,这是可能的(而且很容易)。
Here is an example (from the Qt documentation):
这是一个示例(来自 Qt 文档):
// 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).
基本上,您所要做的就是将指向对象的指针作为第一个参数传递,将方法的地址作为第二个参数(后跟任何其他参数)。
回答by rohanpm
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).
问题是,当您使用指向成员函数的指针时,您还需要以某种方式提供this
参数(即,应该在其上调用成员函数的对象)。
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.
如果您以前没有使用过它,那么它的语法非常困难。阅读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::walkTheDog(int howlong_minutes)
。那么你应该能够使用std::bind1st
并std::mem_fun
使其适用于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.
std::bind1st(std::mem_fun(&Dog::walkTheDog), &dog)
返回一个类似函数的对象,该对象已将成员函数绑定到特定的狗。从那时起,您可以像使用独立函数一样使用它。