D Programming/Mixins

      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

      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;
      }
      
      Last modified on 20 December 2008, at 02:11