Search code examples
typestuplesd

Can the name of the class.tupleof() items be retrieved?


When looping in the result of AnObject.tupleof, I can get the size or the value as a string but can I get more advanced infos over the tuple items (edit) and particularly the original data name (as written in the source class)? The background idea would be to use this property as a kind of RTTI.


Solution

  • .tupleof returns value tuple which is not enough to get field names. Also there is not such thing as "data name", as D does not have any relation between data (== values) and field names, it exists only other way around.

    Some of built-in traits may help though:

    module test;
    
    class Experiment
    {
        class Nested
        {
        }
    
        Nested nested;
        int plain;
        void delegate() skipped;
    }
    
    import std.traits : isCallable, fullyQualifiedName;
    import std.typetuple : Filter;
    
    template allFields(alias T)
    {
        private template combinedFilter(string name)
        {
            // filter out nested type definitions and methods
            // side effect: will filter out delegate/function pointer fields, don't know if listing those makes sense
            mixin("alias field = " ~ fullyQualifiedName!T ~ "." ~ name ~ ";"); 
            enum combinedFilter = !is(field) && !isCallable!field;
        }
    
        alias allFields = Filter!(combinedFilter, __traits(allMembers, T));
    }
    
    void main()
    {   
        pragma(msg, allFields!Experiment);
    }
    

    You can experiment with this code on the fly with this DPaste.

    Probably there is a more simple solution, but given your question wording, most generic approach and small sample of D static introspection power may be of better use.

    Hope I have understood the question right this time.