Thread overview
Named Tuple Names
Mar 26, 2013
Jacob Carlborg
Mar 26, 2013
cal
March 25, 2013
Is there a way to get the names of the fields in a named tuple? It looks like the names are actually aliases.

Thanks,
JC
March 26, 2013
On 2013-03-25 23:58, Jonathan Crapuchettes wrote:
> Is there a way to get the names of the fields in a named tuple? It looks
> like the names are actually aliases.

Perhaps "fieldSpecs".

-- 
/Jacob Carlborg
March 26, 2013
On Tue, 26 Mar 2013 10:13:03 +0100, Jacob Carlborg wrote:

> On 2013-03-25 23:58, Jonathan Crapuchettes wrote:
>> Is there a way to get the names of the fields in a named tuple? It looks like the names are actually aliases.
> 
> Perhaps "fieldSpecs".

Well, that gets you a FieldSpec template which would work except that it is private. I can get around that using the .stringof and then parsing, but I wish there was a cleaner way to do it. If the FieldSpec template was moved into the public section, it would allow for the name member to be accessed.
March 26, 2013
On Tuesday, 26 March 2013 at 16:31:51 UTC, Jonathan Crapuchettes wrote:
> but I wish there was a cleaner way to do it. If the FieldSpec template
> was moved into the public section, it would allow for the name member to
> be accessed.


Not sure this qualifies as clean, but it's an option:

import std.typecons, std.stdio, std.traits, std.conv;

string[] tupleNames(T)()
{
    string[] names;
    uint count = 0;
    bool matchNext = false;
	foreach(m; __traits(allMembers,T))
	{
	    if (matchNext)
	    {
	        names ~= m;
	        matchNext = false;
	        count ++;
	    }

	    if (m == "_" ~ count.to!string)
            matchNext = true;
	}
	return names;

}

pragma(msg, tupleNames!(Tuple!(int,"a",float,"b",string,"c")));

void main(){ }