Looking to overload put operator (<<) recursively

I've been having trouble on how to overload put operator (<<) recursively. I know it's easier that it's supposed to be, but I am still fairly new to recursive thinking.

1
2
3
4
5
6
7
8
9
  ostream& operator<<(ostream& output, RecursionArray& rhs) {
	int i = 10;
	if (i <= 10)
		return output;

	output << "test";
	i++;
	cout << rhs;
  }
resetting i to 10 every time you call the operator won't be helping at all.

descending a fixed number of levels will require the count to be passed in each time, I think you will find this impossible with an operator.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void rec(int level)
{
   if (level==0)
      return;
   else
   {
      cout << "down,";
      rec(level-1);
   }
}

int main()
{
   rec(10);
   rec(99999);
}


remember, every time you recurse it is a completely NEW instance of the function on the stack, they will all have their own "i"

EDIT...
An exception to this is if your recursive function is a member, in which case you could use a member variable as the level counter.
Last edited on
You could also do:

1
2
3
4
ostream& operator<< (ostream& out, type var) {
  int i = 0;
  recursiveFunction(out, var, i);
}


and put all the work inside that recursive function.
Try a static variable:
1
2
3
4
5
6
7
8
9
10
11
12
  ostream& operator<<(ostream& output, RecursionArray& rhs) {
	static int i = 0;
	if (i >= 10)
	{
		i = 0;
		return output;
	}

	output << "test";
	i++;
	cout << rhs;
  }
Topic archived. No new replies allowed.