Why does opDispatch not forward to operators?

Tobias Pankrath tobias at pankrath.net
Wed Aug 7 14:08:23 PDT 2013


import std.stdio;

struct ArrayTypeA {
         int[12] data;
         size_t length() { return 12; }
         auto opSlice(size_t s, size_t e) { return data[s .. e]; }
}

struct ArrayTypeB {
         int[24] data;

         auto opSlice(size_t s, size_t e) { return data[s..  e]; }
         size_t length() { return 24; }
}

struct Array
{
         union {
                 ArrayTypeA a = ArrayTypeA.init;
                 ArrayTypeB b;
         }
         bool isA = true;
         auto opDispatch(string s, T...)(T args)
         {
                 if(isA)
                         return __traits(getMember, a, s)(args);
                 else
                         return __traits(getMember, b, s)(args);
         }
}

void main() {

         Array ar;
         writeln(ar.length); // compiles

          writeln(ar[3 .. 5]); // does not
         // /tmp/test.d(37): Error: Array cannot be sliced with []
}

I'd say, if something rewrites to MyType.opSlice than it's a case 
for opDispatch, too.


More information about the Digitalmars-d-learn mailing list