Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add another example #13

Open
ghost opened this issue Feb 29, 2012 · 2 comments
Open

Add another example #13

ghost opened this issue Feb 29, 2012 · 2 comments

Comments

@ghost
Copy link

ghost commented Feb 29, 2012

Just posted this to the newsgroups and thought it would be worth including in the book as an example:

import std.algorithm;
import std.conv;
import std.string;
import std.stdio;
import std.range;

struct Foo
{
    int one = 1;
    @property int test() { return 1; }
    int three = 3;
    string[string] aa;
    string toString() { return prettyFieldsString(this); }
}

string prettyFieldsString(T)(T t)
    if (is(T == struct) || is(T == class))
{
    Appender!string result;
    Appender!(string[]) fields;
    Appender!(string[]) values;

    foreach (member; __traits(allMembers, T))
    {
        mixin("
        static if (!is( FunctionTypeOf!(t." ~ member ~ ") ))
        {        
            static if (member != " ~ `"toString"` ~ ")
            {
                fields.put(member);
                values.put(to!string(__traits(getMember, t, " ~ `"` ~ member ~ `"` ~ ")));
            }
        }
        ");
    }

    size_t spaceLen = 1;
    foreach (field; fields.data)
        spaceLen = max(spaceLen, field.length);

    alias std.array.replicate replicate;
    string spaceString = replicate(" ", spaceLen);

    foreach (field, value; lockstep(fields.data, values.data))
        result.put(format("%s: %s%s\n", field, replicate(" ", spaceLen - field.length), value));

    return result.data;
}

void main()
{
    Foo foo;
    foo.aa["foo"] = "bar";
    writeln(foo);
}

Sample output: http://paste.pocoo.org/show/558492/

Maybe this has more to do with static introspection than templates, but I thought I'd be nice for the book.

@ghost
Copy link
Author

ghost commented Feb 29, 2012

I forgot to document it though! Do you want me to add some comments to the code?

@ghost
Copy link
Author

ghost commented Feb 29, 2012

I just saw your comment about not being on Github until a few days later. That's ok, in the meantime I'll document the sample. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants