Search code examples
xmlserializationdvariable-names

Possible to get the name of a variable in D?


I am currently trying to write a program in D that when called and passed an object, it will serialize the object into an XML document. I would like to make it as simple as passing the object into it, but I'm not entirely sure it can be done. Example:

class A
{
    //Constructors and fluff
    ....

    int firstInt;
    int secondInt;
}

.....
A myObj = new A();
XMLSerialize(myObj);

and the output would be

<A.A>
    <firstInt></firstInt>
    <secondInt></secondInt>
</A.A>

So, is it possible for me to even get the name of the variables inside of the object or would that have to all be manually done?


Solution

  • Code is worth a thousand words (intentionally simplified):

    import std.stdio;
    
    void print(T)(T input)
        if (is(T == class) || is(T == struct))
    {
        foreach (index, member; input.tupleof)
        {
            writefln("%s = %s", __traits(identifier, T.tupleof[index]), member);
        }
    }
    
    struct A
    {
        int x, y;
    }
    
    void main()
    {
        print(A(10, 20));
    }