When writing wrapped types, you might want to forward methods without subtyping. The opDispatch
method lets that happen with very little code.
To forward methods with opDispatch
, we need to execute the following steps:
Write the wrapped struct.
Write a method called
opDispatch
, which takes variadic arguments:auto opDispatch(string name, T…)(T t)
.In the body, write
return mixin("member." ~ s ~ "(t)");
.
The code has to be executed as follows:
class Foo { int test() { return 0; } void nop() {} } struct Wrapped { Foo f; this(Foo f) { this.f = f; } auto opDispatch(string s, T...)(T t) { return mixin("f." ~ s ~ "(t)"); } } void main() { Wrapped w = new Foo(); Int i = w.test(); w.nop(); }