Stream.opApply and invariance

Michael Coupland mcoupland at gmail.com
Fri Apr 4 22:21:09 PDT 2008


The following example from 
http://www.digitalmars.com/d/2.0/phobos/std_stream.html does not seem to 
compile with the latest D compiler:

	Stream file = new BufferedFile("sample.txt");
	foreach(ulong n, string line; file) {
	  stdout.writefln("line %d: %s",n,line);
	}
	file.close();

The error is due to the D 2.0 string/invariance changes (which I'm still 
trying to wrap my head around; is there a good reference that sorts it 
all out?) [*]

The most literal, valid translation of the above code that I can manage 
is as follows:

	Stream file = new BufferedFile("sample.txt");
	foreach(ulong n, char[] char_ar; file)
	{
		string line = char_ar.idup;
		writefln("line %d: %s",n,line);
	}
	file.close();

although for this particular example, you could just replace string with 
char[]. The problem with that approach is that you usually want a string 
at some point, so you can do all the wonderful string operations that 
one tends to do.

Is this just a case where the Stream library just hasn't been 
string-invariance-ized yet? Or is there a different way to do things 
now? (In which case I recommend updating the documentation!)

	Michael







[*] It's worth noting that there's also an error with 'stdout.writefln' 
hence my replacement with 'writefln' in the second block of code.


More information about the Digitalmars-d-learn mailing list