Search code examples
d

How to declare the variable File.byLine() is assigned to?


I need a class or struct which would look something like

struct ThingReader {
    ???? lines;
    Thing thing;

    this(File f) {
        this.lines = f.byLine;
        popFront;
    }

    @property bool empty()      { return lines.empty; }
    @property ref Thing front() { return thing; }
    void popFront() {
        if (! empty) {
            auto l = lines.front;
            lines.popFront;
            parseLine(l, thing); // Not shown
        }
    }
}

but I don't know what type declaration to put in place where the ???? is.

If I try auto lines then the error is "Error: no identifier for declarator lines".

If I leave the type-inference to the compiler and try something like:

struct ThingReader(Lines) {
    Lines lines;
    Thing thing;

    this(File f) {
        this.lines = f.byLine;
        popFront;
    }
    // etc.
}

then the compiler seems to be fine with this declaration, but when I later try to declare an auto reader = ThingReader(f), I get "Error: struct huh.ThingReader cannot deduce function from argument types !()(File)".

The File.byLine function is declared to return auto but that (see above) does not work for me.

When I declare an auto lines = f.byLine and inspect its type, I can see that it is a ByLine!(char, char).
When I try to declare a ByLine lines, I get "Error: undefined identifier ByLine" and when I try to declare a std.stdio.ByLine lines, I get "Error: undefined identifier ByLine in module std.stdio".
When I try to declare a ByLine!(char, char), I get "Error: template instance ByLine!(char, char) template 'ByLine' is not defined", and std.stdio.ByLine!(char, char) gives me "Error: template identifier 'ByLine' is not a member of module 'std.stdio'".


Solution

  • As mentioned by Adam in the comments, you can use typeof(File.byLine()) to deduce the type you want; it is necessary to add the final parenthesis, which is why typeof(File.byLine) does not work. The reason you cannot explicitly give the type for lines is because the struct returned by the byLine function is private, so cannot be referenced from outside the std.stdio module.