www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - A beginner's question of foreach

reply Alex <faint_u 163.com> writes:
The code snippet from the document page of std.stream can't pass compile:
InputStream s = new BufferedFile(file);

foreach(ulong n, string line; s)
{
	writeln(line);
}

The following are error message:
D:\Tools\d\dmd>dmd cat.d
cat.d(11): function std.stream.InputStream.opApply (int delegate(ref char[]
line)) does not match parameter types (int delegate(ref ulong __applyArg0, ref
invariant(char)[] __applyArg1))cat.d(11): Error: cannot implicitly convert
expression (__foreachbody9) of typeint delegate(ref ulong __applyArg0, ref
invariant(char)[] __applyArg1) to int delegate(ref ulong n, ref wchar[] line)


Any idea? The document needs update?
Dec 29 2007
next sibling parent bearophile <bearophileHUGS lycos.com> writes:
Alex:

I think this question is for the D.learn newsgroup.

This may work:
foreach(n, string line; s)
    writeln(line);


 Any idea?
n is of a different type, I think. Bye, bearophile
Dec 29 2007
prev sibling parent torhu <no spam.invalid> writes:
Alex wrote:
 The code snippet from the document page of std.stream can't pass compile:
 InputStream s = new BufferedFile(file);
 
 foreach(ulong n, string line; s)
 {
 	writeln(line);
 }
 
 The following are error message:
 D:\Tools\d\dmd>dmd cat.d
 cat.d(11): function std.stream.InputStream.opApply (int delegate(ref char[]
line)) does not match parameter types (int delegate(ref ulong __applyArg0, ref
invariant(char)[] __applyArg1))cat.d(11): Error: cannot implicitly convert
expression (__foreachbody9) of typeint delegate(ref ulong __applyArg0, ref
invariant(char)[] __applyArg1) to int delegate(ref ulong n, ref wchar[] line)
 
 
 Any idea? The document needs update?
There's no opApply overload taking an invariant(char)[]. You can use dmd 1.x compilers until things have settled down in 2.x. Or you just use a char[] instead of the string alias. If you need the string to be invariant you can cast it to string before using it. According to the docs for InputStream, opApply is allowed to reuse the char buffer, so depending on your needs, you might have to use .idup or .dup.
Dec 30 2007