A opIndexUnary quiz

bearophile bearophileHUGS at lycos.com
Tue Jan 1 09:52:19 PST 2013


A small quiz (it's a reprise of an older discussion). This code 
compiles with no errors, but do you see anything wrong here?


// -----------------
struct Foo {
     int x;
     alias this = x;
}

class Bar {
     Foo[] data;

     this() {
         data.length = 10;
     }

     Foo opIndex(uint i) {
         return data[i];
     }

     void opIndexUnary(string op)(uint i) if (op == "++") {
         data[i]++;
     }

     void opIndexUnaryRight(string op)(uint i) if (op == "++") {
         data[i]++;
     }
}

void main() {
     auto barfoo = new Bar;
     ++barfoo[3];
     assert(barfoo.data[3] == 1);
     barfoo[3]++;
     assert(barfoo.data[3] == 2);
}
// -----------------


Do you think this code should produce some compilation errors?

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list