multiple `alias this` suggestion
Carl Sturtivant via Digitalmars-d
digitalmars-d at puremagic.com
Wed Apr 19 11:32:43 PDT 2017
Currently only one `alias this` declaration is permitted, and the
documentation https://dlang.org/spec/class.html#AliasThis says
the following.
"Multiple AliasThis are allowed. For implicit conversions and
forwarded lookups, all AliasThis declarations are attempted; if
more than one AliasThis is eligible, the ambiguity is disallowed
by raising an error. Note: Multiple AliasThis is currently
unimplemented."
However the effect of multiple `alias this` declarations can be
approximated in existing D using only single `alias this`, e.g.
in the following three members each with `alias this` are
simulated.
//========================
struct member1
{
int n1, n2, n3;
}
struct member2
{
int n2, n3;
member1 member;
alias member this;
}
struct member3
{
int n3;
member2 member;
alias member this;
}
struct top
{
member3 member;
alias member this;
this(int i, int j, int k)
{
n1 = i; n2 = j; n3 = k;
}
}
void main()
{
auto x = top(1,2,3);
member3 m3 = x.member;
member2 m2 = m3.member;
member1 m1 = m2.member;
import std.stdio;
writefln("%s %s %s", m1.n1, m1.n2, m1.n3);
writefln("%s %s %s", m2.n1, m2.n2, m2.n3);
writefln("%s %s %s", m3.n1, m3.n2, m3.n3);
writefln("%s %s %s", x.n1, x.n2, x.n3);
}
//========================
Which outputs the following as expected from chaining the effects
of `alias this`.
1 0 0
1 2 0
1 2 3
1 2 3
Note that this construction provides a natural hierarchy for name
lookup, unlike the statement above taken from the documentation.
Imagine the existing single `alias this` is extended to provide
such a heierarchy of lookups. For example,
struct top
{
mem3 m3;
mem2 m2;
mem1 m1;
alias m3, m2, m1 this;
// ...
}
could be interpreted to mean search for a name in m3 if not found
in top, and in m2 if not found in m3 and in m1 if not found in
m2. I don't back the syntax, just the notion.
Maybe that's not all that's expected from "multiple alias this"
but it would be a clean step forward. Issues?
More information about the Digitalmars-d
mailing list