Tuesday, 20 May 2014

D - Mixins

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

D - Mixins

Mixins are structs that allows mixing the generated code into the source code. Mixins can be of the following types.
  • String Mixins
  • Template Mixins
  • Mixin name spaces

String Mixins

D has the capability to insert code as string as long as that string is known at compile time. The syntax of string mixins is shown below.
mixin (compile_time_generated_string)
A simple example for string mixins is shown below.
import std.stdio;

void main()
{
   mixin(`writeln("Hello World!");`);
}
When the above code is compiled and executed, it produces result something as follows:
Hello World!
Here is another example where we can pass the string in compile time so that mixins can use the functions to reuse code. It is shown below.
import std.stdio;

string print(string s)
{
   return `writeln("` ~ s ~ `");`;
}

void main()
{
   mixin (print("str1"));
   mixin (print("str2"));
}
When the above code is compiled and executed, it produces result something as follows:
str1
str2

Template Mixins

D templates define common code patterns, for the compiler to generate actual instances from that pattern. Templates can generate functions, structs, unions, classes, interfaces, and any other legal D code. The syntax of template mixins is shown below.
mixin a_template!(template_parameters)
A simple example for string mixins is shown below where we create a template with class Department and a mixin instantiating a template and hence making the the functions setName and printNames available to the structure college.
import std.stdio;

template Department(T, size_t count)
{
   T[count] names;

   void setName(size_t index, T name)
   {
      names[index] = name;
   }

   void printNames()
   {
      writeln("The names");

      foreach (i, name; names) 
      {
         writeln(i," : ", name);
      }
   }
}

struct College
{
   mixin Department!(string, 2);
}

void main()
{
   auto college = College();

   college.setName(0, "name1");
   college.setName(1, "name2");

   college.printNames();
}
When the above code is compiled and executed, it produces result something as follows:
The names
0 : name1
1 : name2

Mixin name spaces

Mixin name spaces are used to avoid ambiguities in template mixins. For example, there can be two variables, one defined explicitly in main and the other is mixed in. When a mixed-in name is the same as a name that is in the surrounding scope, then the name that is in the surrounding scope gets used. This example is shown below.
import std.stdio;

template Person()
{
   string name;
   void print()
   {
      writeln(name);
   }
}

void main()
{
   string name;

   mixin Person a;

   name = "name 1";
   writeln(name);

   a.name = "name 2";
   print();
}
When the above code is compiled and executed, it produces result something as follows:
name 1
name 2

0 comments: