C++绑定方法队列(任务管理器/调度程序?)

Sla*_*a V 2 c++ queue task

是否有方法/模式/库来执行类似的操作(在伪代码中):

task_queue.push_back(ObjectType object1, method1);
task_queue.push_back(OtherObjectType object2, method2);
Run Code Online (Sandbox Code Playgroud)

这样我就可以做一些这样的:

for(int i=0; i<task_queue.size(); i++) {
    task_queue[i].object -> method();
}
Run Code Online (Sandbox Code Playgroud)

所以它会打电话:

obj1.method1();
obj2.method2();
Run Code Online (Sandbox Code Playgroud)

或者这是一个不可能的梦想?

如果有办法添加一些参数来调用 - 这将是最好的.

Doug T.请看这个优秀的答案!

Dave Van den Eynde的版本也很好用.

Dou*_* T. 5

是的,你想要将boost :: bindboost :: functions结合起来,这是非常强大的东西.

这个版本现在编译,感谢Slava!

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <vector>

class CClass1
{
public:
    void AMethod(int i, float f) { std::cout << "CClass1::AMethod(" << i <<");\n"; }
};

class CClass2
{
public:
    void AnotherMethod(int i) { std::cout << "CClass2::AnotherMethod(" << i <<");\n"; }
};

int main() {
    boost::function< void (int) > method1, method2;
    CClass1 class1instance;
    CClass2 class2instance;
    method1 = boost::bind(&CClass1::AMethod, class1instance, _1, 6.0) ;
    method2 = boost::bind(&CClass2::AnotherMethod, class2instance, _1) ;

    // does class1instance.AMethod(5, 6.0)
    method1(5);

    // does class2instance.AMethod(5)
    method2(5);


    // stored in a vector of functions...
    std::vector< boost::function<void(int)> > functionVec;
    functionVec.push_back(method1);
    functionVec.push_back(method2);

    for ( int i = 0; i < functionVec.size(); ++i)
    {         
         functionVec[i]( 5);
    };
    return 0;
};
Run Code Online (Sandbox Code Playgroud)