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

Simulating multiple inheritance with mixin templates


D does not have multiple inheritance like C++. Instead, it follows a Java-style pattern of one base class, multiple interfaces. However, using mixin templates, we can simulate all aspects of multiple inheritance.

How to do it…

We need to execute the following steps to simulate multiple inheritance with mixin templates:

  1. Write an interface and mixin template instead of a base class.

  2. Write your usage class, which inherits from the interfaces and mixes in the mixin templates to the body.

  3. You may override functions from the mixin template by writing new ones with the same name in the class body.

The code is as follows:

import std.stdio : writeln;
interface Base1 {
    void foo();
}

mixin template Base1_Impl() {
  void foo() { writeln("default foo impl"); }
}

interface Base2 {
  void bar();
  void baz();
}

mixin template Base2_Impl() {
  int member;
  void bar() { writeln("default bar impl"); }
  void baz() { writeln("default bazimpl"); }
}

classMyObject...