I have a member function of an object that is typically used in an iterative manner but occasionally in a recursive manner. The function is basically following the path of a stream of water downhill, and under certain conditions the stream could split. In order to support the occasional recursion I have to push the state of the object onto the stack and pop it off afterwords. I'm currently doing this using local variables, but the code looks awful. I'd like to write PushState and PopState members but most of the implementations I've looked at aren't great. e.g. using a stack member in my object which ends up using the heap which is slow and leads to other issues. _alloca won't work as the stack frame is lost when the push function returns.
Are there any other reasonable generic ways of pushing and popping from the stack that i'm missing?
class CMyObject
{
enum Direction
{
left,right,branch,finished;
}
// state variables
double m_XPos,m_YPos;
void Navigate(double x,double y);
Direction GoLeft();
Direction GoLeft();
};
void CMyObject::Navigate(double x,double y)
{
m_XPos = x; m_YPos = y;
Direction d = GoLeft(x,y);
while(d != finished)
{
switch(d)
{
case left: d = GoLeft(); break;
case right: d = GoRight(); break;
case branch:
{
// push object state onto the stack
double temp_x = m_XPos; double temp_y = m_YPos;
Navigate(m_XPos,m_YPos);
// pop object state from the stack
m_XPos = temp_x; m_YPos = temp_x;
GoRight();
} break;
}
}
}