get from tuple by type

Charles Cooper via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 15 16:13:56 PDT 2015


foo[1] is sometimes better, but not always. One has to go back to 
the definition of the thing and literally calculate by hand which 
element of the tuple you want, and then try compiling it, and so 
forth. Although the type system will guarantee that you 
eventually get it right it is a waste of time.

void external_api1_react_to_event(meters_t, time_t);
void external_api2_react_to_event(time_t, meters_t);
alias event_t = Tuple!(time_t, meters_t)
// .. some time later..
external_api1_react_to_event(event_t.get(meters_t), 
event_t.get(time_t));

Yes, I could say
external_api1_react_to_event(event_t[1], event_t[0])
.. but that is barbaric. It's a productivity sink because I have 
to go back to the original definition, align the arguments, and 
then context switch back to whatever I was working on before.

And yes, I could use names. But then you are subject to name 
clashes and using strings instead of types as member identifiers 
is more prone to error anyways. Ever gotten this wrong before --
void CRITICAL_TO_GET_THIS_RIGHT(uint cents, uint dollars);
....
alias params_t = Tuple!(uint, "dollars", uint, "cents");
....
params_t params;
params.dollars = 0;
params.cents = 99;
CRITICAL_TO_GET_THIS_RIGHT(params.expand);
// compilation succeeds, bank fails.

In conclusion: this is an important feature because it allows you 
to enforce type safety when working with tuples (e.g. in function 
parameters) efficiently, without taking too much of the 
programmer's time.

On Sunday, 15 March 2015 at 22:32:48 UTC, bearophile wrote:
> Charles Cooper:
>
>> Is there a better way to do this?
>
> Can you show some use cases for this, and isn't "foo[1]" better?
>
> Bye,
> bearophile



More information about the Digitalmars-d-learn mailing list