Can someone explain how mixin is implemented?

Steven Schveighoffer schveiguy at yahoo.com
Thu May 19 07:02:08 PDT 2011


On Thu, 19 May 2011 09:43:14 -0400, Matthew Ong <ongbp at yahoo.com> wrote:

> On 5/19/2011 2:32 AM, Jacob Carlborg wrote:
>> Template mixins are not exactly like copy and paste code.
>>
>> * You can mixin the same template, at the same location, twice, taking
>> different parameters
>>
>> * Mixed in methods doesn't overload on existing methods in the scope
>> where the mixin is used
>>
>> I think all this is due to mixins being mixed-in in it's own scope.
>>
> Hi Jacob,
>
> The last message confused me. Please clarify.
>  >not exactly like copy and paste code.
> Ok...So, does it meant that the compiler share some sort of binary?
>
> In java using template, the same LinkedList binary is shared for both  
> String class type and also Integer class type.

Java does *not* use templates, they are generics.  A generic seems like,  
but is vastly different from a template.

A template *re-generates* the code as if you substituted the type for the  
given template parameter.

A generic generates one object code file with a base class, and then  
simply enforces the type constraints at compile time when *using* the  
generic.  Under the hood, the generic is compiled with the base class as  
the given type.  It probably avoids doing any type checking at runtime as  
well (since it knows the compiler will check the type for it).

The huge advantages of templates over generics are:

1. The generated type can be fully optimized (footprint and code) for the  
given type parameters.
2. You can execute different code paths depending on the parameter types.
3. You do not have to select a common base class/interface for a group of  
types.  That is, you can select any set of types that will work with your  
template.  With generics, all possible types need to have a common base.
4. Boxing/unboxing is not necessary for non-object types.

The advantage of generics are that you only have one compiled version.   
This is actually very important for bytecode-based languages such as Java  
and C#.

> LinkedList<String> list=new LinkedList<String>();
> LinkedList<Integer> list=new LinkedList<Integer>();
>
> // Can also apply for Account.
> LinkedList<Account> list=new LinkedList<Account>();
>
>
> But there is a single LinkedList Class File(single binary).

Yes, it's a LinkedList with the type given as Object.

-Steve


More information about the Digitalmars-d-learn mailing list