I'm elevating this from D.Learn [1] because I think it needs some input from the language designers.

This code compiles and executes:
-----------------------------------
import std.stdio;

struct StaticRegister {
    static private uint _value;
    @property static uint value() { return _value; }
    @property static void value(uint v) { _value = v; }

    static alias value this;

    static void test() {
        writeln(this.stringof);
        writeln(typeof(this).stringof);
        writeln(this.value);
    }
}

void main(string[] s) {
    // works due to `alias value this`
    StaticRegister = 1;

    StaticRegister.test();
}
-----------------------------------

Output:
StaticRegister
StaticRegister
1



However, this code fails to compile:
-----------------------------------
struct StaticRegister {
    static void test() {
        assert(this is null);
    }
}

void main(string[] s) {
    StaticRegister.test();
}
-----------------------------------

Output:
test.d(5): Error: 'this' is only defined in non-static member functions, not test

To make things more confusing, Bug 380 [2] apparently provided a fix for `this` not evaluating in a static context, but it was a D1 bug and may not apply to D2.

Is `this` overloaded to mean "this class" in a static context or is `this` only valid in a non-static context. Please clarify, and if it's a bug, help me understand so I can make an accurate and actionable bug report.

Thanks for the help,
Mike

[1] - "static alias this" thread on D.Learn - http://forum.dlang.org/post/[email protected]
[2] - Bug 380 - https://issues.dlang.org/show_bug.cgi?id=380

Reply via email to