On 03/14/2012 11:06 PM, Derek Parnell wrote:
On Thu, 15 Mar 2012 08:52:26 +1100, Andrei Alexandrescu
<seewebsiteforem...@erdani.org> wrote:

On 3/14/12 3:00 PM, Simen Kjærås wrote:
template to(T...) {
alias T to;
}

auto from(T...)(T t) {
struct Result { T t; alias t this; }
return Result( t );
}

void main( ) {
int a = 3;
int b = 4;

to!(a, b) = from(b, a);

assert( a == 4 );
assert( b == 3 );
}

I got reborn inside a little when seeing this code. Congratulations!

And I died a little ... I have no idea what this code is doing. What is
the generated code produced by this and why?

I'd like to break the nexus between science and magic here.


// this is used to access language built-in tuples
template to(T...) {
    alias T to;
}

// this builds a struct akin to std.typecons.tuple
// it contains the function parameters as fields t[0], t[1],...
auto from(T...)(T t) {
    struct Result { T t; alias t this; }
    return Result( t );
}

// to!(a,b) creates a tuple containing aliases to a and b

to!(a,b) = from(b,a);   // cannot assign Result to two fields
to!(a,b) = from(b,a).t; // try alias this
auto __tmp = from(b,a).t; // expand tuple assign to multiple assignment
a[0] = __tmp[0], a[1] = __tmp[1];

Reply via email to