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

后端 未结 2 1590
青春惊慌失措
青春惊慌失措 2020-12-14 10:08

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?

2条回答
  •  情深已故
    2020-12-14 10:15

    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.

提交回复
热议问题