opIndexCall

Derek Parnell derek at psych.ward
Sat Mar 24 22:01:11 PDT 2007


On Sat, 24 Mar 2007 13:52:12 -0400, Dan wrote:

> I've recently discovered the want for an opIndexCall override in D.
It seems that all you need to do is get the return type of the opIndex
right. Here is my pretend example...

import std.stdio;
struct Y {
  Y function() f;
}

struct X {
  char[][] keys;
  Y[] values;

  // Has to return a function pointer.
  Y function() opIndex(char[] idx)
  {
     foreach(int i, char[] s; keys)
     {
         if (s == idx)
            return (values[i].f);
     }
     return null;
  }


  void opIndexAssign(Y function() fp, char[] idx)
  {
     foreach(int i, char[] s; keys)
     {
         if (s == idx)
         {
            values[i].f = fp;
            return;
         }
     }
     values.length = values.length + 1;
     (values[$-1].f) = fp;
     keys ~= idx;
  }
}

Y myF(){
  Y y;
  writefln("Got it");
  return y;
}

void main()
{
    X z;

    z["hello"] = &myF;

    z["hello"](); // <-- No worries, mate.

        Y function() a; // have to do this?
    a = z["hello"];  // and this
    a();                 // and this?
}


-- 
Derek Parnell
Melbourne, Australia
"Justice for David Hicks!"
skype: derek.j.parnell



More information about the Digitalmars-d mailing list