Applying a tuple to a function (and more)
Juanjo Alvarez
juanjux at gmail.com
Sat Sep 18 18:43:09 PDT 2010
Philippe Sigaud wrote:
>> 1. Having the strings, defined at compile time, "MyClass" and "mymethod",
>> how could I could I get to a delegate to MyClass.mymethod?
>>
>
> You can insert them in a piece of code as a string, and then mix it in:
>
> 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).
>> 2. Is there any way to apply a tuple to a function, expanding as
>> arguments?
> 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);
}
auto tup = tuple(42, 3.14);
f(1, tup.expand);
//
Wonderful. I wish it was better documented on
http://digitalmars.com/d/2.0/phobos/std_typecons.html
> As for expanding tuples inside functions if you do that regularly, I
> suggest you use a function adaptor, like this:
>
> template tuplify(alias fun) if (isCallable!fun)
> {
> ReturnType!fun tuplify(Tuple!(ParameterTypeTuple!fun) tup)
> {
> return fun(tup.expand);
> }
> }
Nice to know. I got you excellent explanation.
Thanks * 100,
Juanjo
More information about the Digitalmars-d-learn
mailing list