What do you use opDispatch for?

Philippe Sigaud philippe.sigaud at gmail.com
Sun Mar 21 07:02:09 PDT 2010


OK, I know opDispatch just appeared in DMD, but I remember a *huge* thread on it, where people were jumping up and down waiting for it.

Me, I have no wonderful idea, though I feel some potential in it.
The only interesting use I found for now is making a class/struct extensible:

mixin template Extensible()
{
    auto opDispatch(string s, T...)(T ts)
    {
        mixin("return " ~ s ~ "(this, ts);");
    }
}

So given:

class C { 
    mixin Extensible;
}

and 

class D : C {} // (D inherits from C's extensibility).

If can 'add' methods to C and D by defining external functions: 

int foo(C c, int i) { return i;}
C c = new C;
c.foo(3); // becomes foo(c, 3).

It allows me to imitate what the compiler does for arrays:

"abc".toupper.reverse; // -> "CBA"

This functions can be templated, giving a new functionality to all extensible classes:

string typeof(C)(C c) { return C.stringof;}

C build(C, T...)(C c, T t) if (is(C == class)) { return new C(t);}
C build(C, T...)(C c, T t) if (is(C == struct)) { return C(t);}

bool isSubtypeOf(C, D)(C c, D d) if (is(C : D)) { return true;}
bool isSubtypeOf(C, D)(C c, D d) if (!is(C : D)) { return false;}

etc.

So, is this a good idea or not? I use something like .build to map factory functions on struct ranges, building another range of structs with different values, but I do not _need_ mixin Extensible for this...

As for you, what are your experiences / projects with opDispatch?

Philippe


More information about the Digitalmars-d-learn mailing list