static alias this
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Feb 7 14:36:38 PST 2015
On 02/07/2015 04:46 AM, Mike wrote:
> B)-----------------------------------------
> struct StaticRegister {
> static private uint _value;
> @property static uint value() { return _value; }
> @property static void value(uint v) { _value = v; }
>
> alias value this;
> }
>
> void main(string[] s) {
> StaticRegister = 1;
> assert(StaticRegister == 1);
> }
> -------------------------------------------
>
> ... the assignment error is eliminated, but the read is not.
I bet it's an unintentional implementation artifact. Assigning to a type
doesn't make sense to me.
> I argue that either both errors should be eliminated, or neither should
> be eliminated.
It is not hard to create strange D code. I recommend the following
lightning talk for fun. :) Brian Schott at DConf 2014:
http://www.youtube.com/watch?v=oF8K4-bieaw#t=1620
> Now, in the example below, `this` is referring to the type itself in a
> static context
Not exactly "type itself" because you apply typeof() to it later below.
I this 'this' means "the type of the object if it were not a static
function". :/
> C)-------------------------------------------
> import std.stdio;
>
> struct StaticRegister {
> static string GetType() { return typeof(this).stringof; }
> }
>
> void main(string[] s) {
> writeln(StaticRegister.GetType());
> }
> -------------------------------------------
>
> So, it follows that the example below should work... and it does
> D)-------------------------------------------
> struct StaticRegister {
> static private uint _value = 0;
> @property static uint value() { return _value; }
> @property static void value(uint v) { _value= v; }
>
> static uint GetValue() {
> return this.value;
That works by accident. I am surprised that 'this' works in a static
function. In any case, it should better be null.
Ok, it's good that 'this' is not available:
assert(this is null);
Error: 'this' is only defined in non-static member functions, not foo
Phew... :) So, 'this.value' works by accident because the compiler
reaches for *static* value() without evaluating 'this'.
Ali
More information about the Digitalmars-d-learn
mailing list