www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Operator overloading inconsistencies

I am of the possibly misguided opinion that the if the expression x.opIndex(i) 
evaluates to V then x[i] should should also evaluate to V. I have however found 
two situations in which this does not happen. The first is when you have a 
pointer to a struct. The second is when opIndex is a delegate within a struct:

   struct Ex1
     int[4*4] data;
     int opIndex(int i, int j) { return data[i + j*4]; }

   struct Ex2
     int[4*4] data;

     int delegate(size_t i, size_t j) opIndex;
     int opIndexA(size_t i, size_t j) { return data[i + j*4]; }
     int opIndexB(size_t i, size_t j) { return data[j + i*4]; }

   Ex1  e1;
   Ex1* e2;
   e2 = &e1;
   Ex2  e3;
   e3.opIndex = &e3.opIndexA;

   e1[1,0]; // sure; not a problem
   e2[2,0]; // only one index allowed to index Ex1 *
            // [i] has no effect in expression ((e2)[2])
   e3[3,0]; // no [] operator for type Ex2

   e1.opIndex(1,0); // sure; not a problem
   e2.opIndex(2,0); // sure; not a problem
   e3.opIndex(3,0); // sure; not a problem

I certainly understand why the above occurs. I thought I would mention this 
inconsistency so that anyone who had not noticed would have a chance to think
over. Anyone else who has noticed another case of x.opIndex(i) not working with 
x[i] might also want to explain how it happened.
Aug 22 2006