On Sunday, 8 February 2015 at 00:31:42 UTC, Mike wrote:
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

`this` should not exist within a static member function. The fact that this code compiles is probably a bug. `StaticRegister = 1` is almost definitely not intended behaviour, and I don't know about `static alias value this`.


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

This is correct behaviour.


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.

`this` should only be valid in a non-static context, as far as I know. That's pretty much what static means: "there is no `this`".

Reply via email to