On Sunday, 25 September 2016 at 16:26:11 UTC, Basile B. wrote:
On Sunday, 25 September 2016 at 16:07:59 UTC, Basile B. wrote:
On Sunday, 25 September 2016 at 09:01:44 UTC, Namespace wrote:
On Sunday, 25 September 2016 at 04:54:31 UTC, grampus wrote:
Dear all
For example, I have a struct
struct point{int x;int y}
point a;
Is there an easy way to access x and y by using a["x"] and
a["y"]
I guess I need to overload [], but can't figure out how.
Someone can help? Thank you very much
----
import std.stdio;
struct Something
{
int x, y;
float z;
auto opIndex()(string member) {
switch (member) {
case "x": return this.x;
case "y": return this.y;
case "z": return this.z;
default: assert(0);
}
}
}
void main(string[] args)
{
Something s;
writeln(s["x"]);
writeln(s["z"]);
}
----
WooW I have to say that I'm mesmerized !
How can this works ? "member" is run time variable so the
return type shouldn't be inferable.
Ther's no trick related to compile time:
import std.stdio;
struct Something
{
int y;
float z;
double e;
float x = 1234;
auto opIndex()(const(char)[] member) {
switch (member) {
case "x": return this.x;
case "y": return this.y;
case "z": return this.z;
case "e": return this.e;
default: assert(0);
}
}
}
void main(string[] args)
{
Something s;
char[] member = "w".dup;
member[0] += args.length;
writeln(s[member]);
}
Can we get an explanation from a compiler guy ? It seems the
the switch statement is already evaluated at compiled time...
"return" in "case" can infer...TIL. That's still a bit strange
from the ABI point of view...because it means that under win32 it
knows that z and x have to be returned in ST0, y in EAX...but
cases are known at compile time...ok I think I get it :].
Depending on a static case, another CPU register is filled...