継承

Last-modified: 2012-06-15 (金) 17:26:23

Dは継承を実現するためのさまざまな仕組みを持っている

クラスによる継承

ポリモーフィズムを実現できる
多重継承はできない

class Base { }
class Foo : Base { }
Base foo = new Foo();

ミックスインによる継承

機能ごとに分けておき、組み込んで利用する

mixin template Feature() {
  void fMethod() { }
  int fVar;
}
class Bar {
  mixin Feature;
}
Bar bar = new Bar;
bar.fMethod();
bar.fVar = 1;
class Bar2 { // Bar を継承しない
  mixin Feature;
}
Bar2 bar2 = new Bar2; // もちろん上と同じように使える
bar2.fMethod();
bar2.fVar = 1;

多重継承に近いこともできる

class Bar2 {
  mixin Feature;
  mixin Feature2;
}

alias this による委譲

クラスじゃないものや、変更できない型を継承して拡張できる

struct Type {
  void method(){ }
}
class MyType {
  Type core;
  alias core this; // core のメンバやプロパティを自分のもののように参照できるようにする
  void myMethod();
}
MyType boo = new MyType;
boo.myMethod();
boo.method();

応用

struct MyType(T) {
  T core;
  alias core this;
}
alias MyType!(int) MyInt;
MyInt i;
i = 0; // i.core = 0;

UFCS

継承ではないけど、これだけで足りる場合もある

@property void print(int n)  { }
1.print; // = print(1);