On Monday, 4 May 2015 at 14:33:23 UTC, Baz wrote:
the following program fails because of the `put` function :
---
import std.stdio;
import std.range;
size_t readN(T, Range)(ref Range src, ref Range dst, size_t n)
if (isInputRange!Range && isOutputRange!(Range, T))
{
size_t result;
while(1)
{
if (src.empty || result == n)
break;
put(dst, src.front()); // here
src.popFront;
++result;
}
return result;
}
void main(string[] args)
{
int[] src = [1,2,3];
int[] dst = [0];
auto n = readN!int(src, dst, 2);
writeln(dst);
}
---
If i replace `put` by a cat op (`~`) it works, however the cat
op only works here because i test the template with two int[].
What's wrong ?
Your destination is too small. When arrays are treated as output
ranges, they get written to like a buffer. They don't get
appended to. If you want to append to them, then use Appender for
the output range.
On a side note, it's very backwards that you're calling front
with parens and popFront without. front is usually a property
function (in which case, if @property ever gets sorted out
properly, front() wouldn't compile), and popFront is never a
property function (so you _can_ call it without parens, but it's
kind of weird to do so).
- Jonathan M Davis