how do I get the ith field of a std.typecons.Tuple ?
Timothee Cour
thelastmammoth at gmail.com
Sun Aug 18 02:26:16 PDT 2013
On Sun, Aug 18, 2013 at 2:15 AM, John Colvin <john.loughran.colvin at gmail.com
> wrote:
> On Sunday, 18 August 2013 at 08:46:17 UTC, Timothee Cour wrote:
>
>> A)
>> how do I get the ith field of a std.typecons.Tuple ?
>> ideally, it should be as simple as:
>>
>> auto t=Tuple!(int,"name",double,"**name2")(1);
>> static assert(t.fields[0] == "name");
>>
>
> field is the old name for expand, retained for compatibility, it's not
> recommended. It gives you direct access to the tuple inside the Tuple
> struct, but it's for getting the variable values, not their names.
>
I didn't mean Tuple.field (as in Tuple.expand), I really meant the name of
the corresponding entry, as shown in my example.
If you want to get the *names* you've chosen for the tuple fields, you'll
> have to use traits of some sort I think.
>
I don't see how that would work, however I've figured out how to do it:
That's a bit of a hack, but should work. Should it be included in phobos,
or, better, shall we fix Tuple with some of the recommendations i gave
above?
----
import std.typecons;
auto tupleField(T,size_t i)()if(isTuple!T && i<T.length){
enum foo0=typeof(T.init.slice!(i,i+1)).stringof;
static assert(foo0[$-2..$]==`")`);//otherwise not a tuple with fields
enum foo=typeof(T.init.slice!(i,i+1)).stringof[0..$-2];
size_t j=foo.length;
while(true){
char fj=foo[--j];
if(fj=='"')
return foo[j+1..$];
}
}
unittest{
import std.typecons;
auto t=Tuple!(int,"foo",double,"bar")(2,3.4);
alias T=typeof(t);
static assert(tupleField!(T,0)=="foo");
static assert(tupleField!(T,1)=="bar");
}
----
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20130818/e8b7cd43/attachment.html>
More information about the Digitalmars-d-learn
mailing list