Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Forwarding methods with opDispatch


When writing wrapped types, you might want to forward methods without subtyping. The opDispatch method lets that happen with very little code.

How to do it…

To forward methods with opDispatch, we need to execute the following steps:

  1. Write the wrapped struct.

  2. Write a method called opDispatch, which takes variadic arguments: auto opDispatch(string name, T…)(T t).

  3. 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();
}

How it works…

We've been using alias this throughout the chapter to provide easy access to a wrapped data member or property. However, since this also enables implicit casting to the wrapped type, we don't always want it. Using...