alias this on module
Jonathan Marler via Digitalmars-d
digitalmars-d at puremagic.com
Mon May 1 17:01:16 PDT 2017
On Monday, 1 May 2017 at 23:06:00 UTC, Petar Kirov [ZombineDev]
wrote:
> The common thing between modules and the other aggregate types
> (classes, interfaces, unions and structs) is that members of
> the former behave as if they were static members of the later.
> The difference, of course, is that since modules can have only
> static members, they can't be instantiated and by extension
> have no 'this' pointer/reference. Because of this I think
> 'alias member this' on the module level would be nonsensical.
> Keep in mind that 'alias member this' is a tool for
> establishing a subtyping relationship - i.e. 'this' instance
> can be used wherever 'member' can be used - and not just a way
> to do member access rewrite like opDispatch. There is no
> subtyping relationship between namespaces, which is what
> modules are effectively​.
>
> On the other hand, 'alias bar = foo.bar' and module level
> static opDispatch seem like perfectly reasonable and desirable
> features.
It's true that "this" normally refers to an instance of a type,
but that's not the case with "alias this". It's actually
referring to the type itself, not an instance, so you can access
static members through it. I've written an example that compiles
and works to demonstrate this:
import std.stdio;
struct Foo
{
int x;
}
struct fakemodule
{
// a member of the fake module
// Note that it has to be "static" to be analagous to a real
module
static Foo foo;
// an "alias this" on the module (this isn't supported on a
real module)
alias foo this;
}
void main()
{
fakemodule.x = 3; // references fakemodule.foo.x
// Print x using alias this and direct access
writeln(fakemodule.x);
writeln(fakemodule.foo.x);
// Verify these expressions represent the same thing
assert(&fakemodule.x == &fakemodule.foo.x);
}
More information about the Digitalmars-d
mailing list