gpt4 book ai didi

c++ - 使用对象 vector 调用接口(interface)函数的 Clean 方法

转载 作者:行者123 更新时间:2023-11-28 00:54:52 26 4
gpt4 key购买 nike

我有一个实现相同接口(interface)的任务 vector 。我有一个可以执行多个任务的状态机对象,而且我有一大堆事件。如果调用特定事件,我希望该事件调用一个函数到“ProcessTasks”,其中 ProcessTasks 获取需要调用的特定接口(interface)函数,并为每个任务调用该函数。我想避免在每个事件函数中使用巨大的 case 语句或重复 for 循环迭代,但我不确定该怎么做。是否有允许我这样做的构造/方法,或者 case 语句方法是最好的方法,还是在每个函数中抛出循环最好?

谢谢:)

示例(我的状态模式中的单个状态类 sm ):

State_e StateIdle::EVENT_REQUEST_STOP_()
{
ProcessTasks( HandleStopFn );
return STATE_STOPPED;
}

// -- more events

/* desired solution allows me to have to implement
the loop only once, but be able to call any of
the functions in the interface, for any number of events */

for( vector<TaskPtr>::iterator it = m_tasks.begin(); it != m_tasks.end(); ++it )
{
it->HandlerFunction()
}

//TaskPtr是boost auto ptr,实现了这个缩短的接口(interface)

class Task
{
void HandleActiveFn() = 0;
void HandleStopFn() = 0;
};

最佳答案

您可以将函数绑定(bind)到 std::function,然后遍历 vector (或使用 std::for_each)调用函数并将指针传递给每个元素作为第一个参数。例如,这是绑定(bind)成员函数并在类型的实例上调用它们的方法:

#include <functional>
#include <iostream>
#include <vector>
#include <algorithm>

struct IFoo
{
virtual void foo1() const = 0;
virtual void foo2() const = 0;
};

struct Foo : public IFoo
{

virtual void foo1() const {
std::cout << "Foo::foo1\n";
}
virtual void foo2() const {
std::cout << "Foo::foo2\n";
}
};

int main() {

std::function <void(IFoo*)> f1 = &IFoo::foo1;
std::function <void(IFoo*)> f2 = &IFoo::foo2;

std::vector<IFoo*> foos{new Foo(), new Foo(), new Foo()};

std::for_each(foos.begin(), foos.end(), f1);

std::for_each(foos.begin(), foos.end(), f2);

}

如果您按值而不是指针存储元素,您可以使用 std::mem_fn :

auto f1 = std::mem_fn(&Foo::foo1);
auto f2 = std::mem_fn(&Foo::foo2);

std::list<Foo> foos = ....;

std::for_each(foos2.begin(), foos2.end(), f1);

关于c++ - 使用对象 vector 调用接口(interface)函数的 Clean 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12057176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com