Вопрос

I am in progress of writing a render system in D2, but it is really annoying me that D prefers its own monitor class object.Object.Monitor (Which I never imported by the way) over my own Monitor class.

What's a way to prevent D from using its monitor class instead of mine? I know I could append the conventional underscore, or simply use its full name (myapp.graphics.x11.Monitor) but this class will be used an awful lot, so these fixes aren't really ideal.

module app;

class Monitor {
    public Monitor returnMe() {
        return this; // Error: cannot implicitly convert expression (this) of type app.Monitor to object.Object.Monitor
    }
}


void main() {
    Monitor monitor = new Monitor;
    monitor.returnMe();
}
Это было полезно?

Решение

I think this is because inside the class Monitor, your class name doesn't quite exist yet so the compiler thinks the already existing Monitor (it is in object.d which is auto imported) is a better match.

I actually think this should be considered a compiler bug, since if the other Monitor didn't exist, this code would indeed work. edit: Actually, since Monitor is a nested class in Object, this is /not/ a compiler bug, nested names always override outer names. So it is just weird that Object base class has a nested one called Monitor. /edit

But to work around the thing for now, you can use typeof(this) inside the Monitor class instead of its name. That will disambiguate inside, and the outside code still works correctly:

module app;

class Monitor {
     // changed the name only inside the class
    public typeof(this) returnMe() {
        return this;
    }
}


void main() {
     // works normally here
    Monitor monitor = new Monitor;
    monitor.returnMe();
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top