Template classes
    Jarrett Billingsley 
    jarrett.billingsley at gmail.com
       
    Wed Apr 15 09:21:41 PDT 2009
    
    
  
On Wed, Apr 15, 2009 at 12:13 PM, Arild Boes <aboesx at gmail.com> wrote:
>> Take a look at the 'this' of D2, it allows to create wrapper structs, so
>> you can just add methods to the built-in arrays.
>>
>> Bye,
>> bearophile
>
> Please elaborate on this. How does one do that?
With the new, delicious "alias this."
struct Array(T)
{
	T[] blah;
	alias blah this; // woo!
	
	void print()
	{
		writefln(blah);
	}
}
void main()
{
	Array!(int) x;
// anything not defined in Array will instead be looked up in the
'alias this' member
	x.length = 5;
	x[2] = 3;
	x.print();
}
Though actually I'm not sure why bearophile suggested this, since even
in D1, you can define 'extension' methods for arrays and AAs by simply
declaring a function that takes an array or AA as its first parameter.
 It's syntactic sugar for a normal function call.  By taking advantage
of templates and IFTI you can make these methods work for all kinds of
arrays.
void print(T)(T[] arr)
{
	writefln(arr);
}
void main()
{
	int[] x;
	x.length = 5;
	x[2] = 3;
	x.print(); // same as print(x);
}
This will work in D1 or D2.
    
    
More information about the Digitalmars-d-learn
mailing list