Jarrett Billingsley skrev:
On Wed, Apr 15, 2009 at 12:13 PM, Arild Boes <abo...@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.

I see. Thank you very much for that answer.
Actually the f-call syntactic sugar seems like a good way to keep core classes of any library very lean and mean, whilst maintaining the ability to expand the module without re-compiling the original library! (just import this guy, and the new functions will be available to you as if declared in the original type).

Reply via email to