C++ 绑定方法队列(任务管理器/调度程序?) [英] C++ bound method queue (task manager/scheduler?)

查看:71
本文介绍了C++ 绑定方法队列(任务管理器/调度程序?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有方法/模式/库可以做这样的事情(在伪代码中):

Is there a method/pattern/library to do something like that (in pseudo-code):

task_queue.push_back(ObjectType object1, method1);
task_queue.push_back(OtherObjectType object2, method2);

这样我就可以这样的事情:

so that I could do the something like:

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

这样它就会调用:

obj1.method1();
obj2.method2();

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

Or is that an impossible dream?

如果有一种方法可以添加多个要调用的参数 - 那将是最好的.

And if there's a way to add a number of parameters to call - that would be the best.

Doug T. 请看这个很好的答案!

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

推荐答案

是的,您希望结合 boost::bindboost::functions 非常强大的东西.

Yes you would want to combine boost::bind and boost::functions its very powerful stuff.

这个版本现在可以编译了,感谢 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;
};

这篇关于C++ 绑定方法队列(任务管理器/调度程序?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆