Jump to content

D Programming/Mixins

From Wikibooks, open books for an open world

A mixin is the possibility to make a copy of a template to a specified place.

template t(T){
  T get(){
    return mValue;
  }
}

This alone makes no sense. But if you want to insert it into a class, which has got a member variable mValue this can make sense.

class C{
  private int mValue;
  mixin t!(int);
}

You can use mixins to assemble a class out of pieces.

Make an outer class know the mixin

[edit | edit source]

If you need a way to make your mixin known to the outer class, you can use static constructors.

template t(T){
  static this(){
    sMixinCounter++;
  }
}

class C{
  private static int sMixinCounter;
  private int mValue;
  mixin t!(int);
}

If you want to use multiple of such mixin, they have to be named, to avoid linker errors.

class C{
  private static int sMixinCounter;
  private int mValue;
  mixin t!(int) t1;
  mixin t!(int) t2;
}