I have a vector of tasks implementing the same interface. I have a state machine object that can have multiple tasks, and I have a whole bunch of events. If a particular event is called, I would like the event to call a function to ‘ProcessTasks’ in which ProcessTasks takes the particular interface function that needs to be called, and calls that function for every task. I would like to avoid having a giant case statement or repeating the for loop iteration in every event function, but I’m not sure how to. Is there a construct/approach that allows me to do this, or is the case statement approach the best method, or the toss the loop in each function best?
Thanks : )
Sample Example ( a single state class in my state patterned 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 is boost auto ptr and implements this shortened interface
class Task
{
void HandleActiveFn() = 0;
void HandleStopFn() = 0;
};
Provide a
privatemember function inStateIdlethat accepts aTaskmember function pointer and usestd::for_eachto invoke the member function on each of theTaskinstances:See demo http://ideone.com/A4c5U .
If you wanted to avoid a
switchyou could construct a function table using astd::map:And to call:
which you may prefer to: