www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Range question

I'm trying to write a range-based template that iterates over a range
and returns one of its elements according to some criterion:

	ElementType!R choose(R, E)(R range)
		if (isInputRange!R)
	{
		ElementType!R e;
		while (!range.empty) {
			if (/* some criterion */) {
				e = range.front;
			}
			range.popFront();
		}
		return e;
	}

But how do I guarantee that e won't be overwritten? For example, if
range.front returns a reference to some buffer that later gets
overwritten by a subsequent operation. Or, if it does get overwritten,
how can I make a copy of its value without depending on specific element
types?

Note that e may be assigned multiple times during the loop, and it's
unknown in advance when the value of e will stop changing, so inserting
a return in the if condition is not possible.


T

-- 
There's light at the end of the tunnel. It's the oncoming train.
Feb 17 2012