Applying a tuple to a function (and more)

Philippe Sigaud philippe.sigaud at gmail.com
Sat Sep 18 22:34:03 PDT 2010


On Sun, Sep 19, 2010 at 03:43, Juanjo Alvarez <juanjux at gmail.com> wrote:

> > enum string code = "auto deleg = &" ~ className ~ "." ~ methodName ~ ";";
> > // auto deleg = &MyClass.mymethod;
> > mixin(code); // created deleg, you're good to go.
>
> I tried it and worked like a charm (but I've changed my code so instead of
> two strings to class + method, a fully qualified non member function
> address
> is used so I have a little more flexibility).
>

String mixins are quite powerful, if a bit clunky at times.

See also __traits(getMember, ...)
http://digitalmars.com/d/2.0/traits.html   (look for getMember)



> > Use the .field or .expand alias, exposed by Tuple!() to get a direct
> > access to the internal expression tuple.
> >
> > f(tup.expand); // cracks tup open
>
> Now, that is exactly what I wanted. It even works if the function has
> aditional arguments before the expanded tuple one's:
>
> //
> void f(int a, int b, double c) {
>   writeln(a); writeln(b); writeln(c);
> }
>


Yes, because tuple.expand is directly the expression tuple stored inside
Tuple!(...)
When you have a typetuple in a template, like this:

template List(T...)
{
}

The T... part is a typetuple: an array of types, if you wish. You can get
its length, index it, slice it, iterate on it, etc.
You can have a variable with this strange 'type' and also get its length,
etc.

template List(T...)
{
    T t;
}

t is an expression tuple. std.typecons.Tuple is nothing more than the
preceding List!(...), with a few more functionalities.
So, something interesting is that when you do tup.expand, you obtain a bunch
of values of different types, all perfectly individually typed and usable.
You can get one by indexing, slice it, etc.

So, given your new f, you can even do:

auto tup = tuple(42, 3.14);
f(tup.expand[0], 1, tup.expand[1]);

Though in this particular case, it's cleaner to do:

f(tup[0], 1, tup[1]);


Wonderful. I wish it was better documented on
> http://digitalmars.com/d/2.0/phobos/std_typecons.html
>
>
Yes, typecons.Tuple has lot of nifty things going for it, but there are not
all documented.
You can open a bug/enhancement request at http://d.puremagic.com/issues/



> Nice to know. I got you excellent explanation.
>
> Thanks * 100,
>
>
My pleasure,

Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100919/df0cf332/attachment.html>


More information about the Digitalmars-d-learn mailing list