how to access struct member using [] operator?

Basile B. via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Sep 25 01:08:24 PDT 2016


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

You can't do that. There's a problem because the string passed is 
not known at compile-time, so the return type of "opIndex(string 
member)" cannot be inferred.

It works only for one type:

°°°°°°°°°°°°°°°°°°°
import std.stdio;

struct Something
{
     int x,y;
     float z;

     int opIndex(string member)
     {
         alias T = typeof(this);
         foreach(m;__traits(allMembers, T))
         if (m == member)
         {
             static if (is(typeof(__traits(getMember, T, m)) == 
int))
                 return __traits(getMember, T, m);
         }
         assert(0);
     }
}

void main(string[] args)
{
     Something s;
     writeln(s["x"]);
}
°°°°°°°°°°°°°°°°°°°

If you add a template parameter to opIndex then you can't call it 
with the array syntax so it becomes pointless to use an operator 
overload.


More information about the Digitalmars-d-learn mailing list