Search⌘ K

opDispatch() and opBinaryRight()

Explore how to implement catch-all member handling with opDispatch, which intercepts calls to non-existent object members, and customize the behavior of the in operator using opBinaryRight for user-defined types. Understand how these operator overloads enhance code flexibility and enable intuitive container checks in D programming.

Catch-all operator opDispatch()

opDispatch gets called whenever a missing member of an object is accessed. All attempts to access non-existent members are dispatched to this function.

The name of the missing member becomes the template parameter value of opDispatch.

The following code demonstrates a simple definition:

D
import std.stdio;
struct Foo {
void opDispatch(string name, T)(T parameter) {
writefln("Foo.opDispatch - name: %s, value: %s",
name, parameter);
}
}
void main() {
Foo foo;
foo.aNonExistentFunction(42);
foo.anotherNonExistentFunction(100);
}

There are no compiler errors for the calls to non-existent members. Instead, all of those calls are dispatched ...