因此,我首先进行了大量的谷歌搜索,但所有解决方案似乎都异常复杂。所以,我想我应该在这里问一下,看看这项任务是否真的需要我遇到的那种方法......
所以,假设我有一个 Event
类。我希望它有一个 time
变量和一个 functionToExecuteAtTime
函数指针/变量/神奇的代码,让我可以将任何旧函数传递给此类。
此外,我希望将事件保存在优先级队列中,该队列按时间顺序排列事件并执行它们“携带”的功能。但是暂时忘记这个
类似这样的事情...
class Agent
{
public:
int id;
float cash;
Agent::Agent
{
cash = 100;
}
}
class uberSystem
{
public:
float assets;
int supplyOfDeadlyPoison;
float poisonCost;
std::vector<Agent> agents;
uberSystem::uberSystem
{
assets = 100000;
supplyOfDeadlyPoison = 100000;
poisonCost = 8;
for(int i = 0; i < 100; i++)
{
Agent newAgent;
newAgent.id = i;
agents.push_back(newAgent)
}
}
};
class Event
{
public:
int time;
SOMETHING_THAT_LETS_ME_HOLD_FUNCTIONS myFunction;
Event::Event(int t, SOMETHING_THAT_LETS_ME_HOLD_FUNCTIONS func)
{
time = t;
myFunction = func;
}
}
int uselessFunction()
{
return 42;
}
void buyPoisonAndKillAgent(Agent &myAgent, uberSystem &mySystem)//obviously not good...
{
myAgent.cash -= mySystem.poisonCost;
mySystem.assets += mySystem.poisonCost;
mySystem.agents.erase(mySystem.agents.begin()+myAgent.id);
mySystem.supplyOfDeadlyPoison -= 1;
}
int main()
{
uberSystem newSystem;
// Event newEvent(100, uselessFunction());//make a new event
Event newEvent(100, buyPoisonAndKillAgent(newSystem.agents[5], newSystem));
newEvent.myFunction;//run the bloody function
return 0;
}
好吧,现在看来这简直是我一厢情愿的想法。那么,我怎样才能实现这一目标呢?函数指针是正确的选择吗?还是有一些我还没有找到的更好的方法?
哦,显然我毕竟有 std::function
可用......我一直都没有处于石器时代!
谢谢!
最佳答案
您可以有一个基类事件(由@EdHeal提议),然后有一个模板化子类来存储您的函数指针:
class Event {
public:
int time;
Event(int t) : time(t) {}
virtual ~Event(){}
virtual void myFunction() = 0;
};
template<typename TFunc>
class TEvent : public Event {
public:
TFunc func;
TEvent(int t, TFunc f) : Event(t), func(f) {}
void myFunction() { func(); }
};
template<typename TFunc>
auto_ptr<Event> make_event(int time, TFunc func) {
return std::auto_ptr<Event>(new TEvent<TFunc>(time,func));
}
使用辅助函数make_event
,可以轻松调用并自动推断类型:
void useless() {std::cout << "Func A";}
struct functor {
void operator()() {std::cout << "Functor B";}
};
struct paramFunctor {
paramFunctor(int x, double y): result(0), m_x(x), m_y(y){}
void operator()() {
std::cout << "Params: x:" << m_x << ", y:" << m_y << "\n";
}
long long result;
private:
int m_x;
double m_y;
};
int main() {
auto_ptr<Event> e1 = make_event(10,useless);
auto_ptr<Event> e2 = make_event(100,functor());
auto_ptr<Event> e2 = make_event(100,paramFunctor(1,2.0));
// your code goes here
e1->myFunction();
e2->myFunction();
e3->myFunction();
return 0;
}
当然,如果可以访问 C++11(或 TR1 或 boost),则根本不需要所有这些(如其他答案所述)
关于c++ - 如何实现一个简单的事件队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26175588/