Post-ctor ctor

Andrej Mitrovic andrej.mitrovich at gmail.com
Mon Aug 8 14:05:59 PDT 2011


Done deal:

import std.traits;

string FieldInit(T, int len, string fun)()
{
    string result;
    auto fields = [__traits(allMembers, T)];

    result ~= "this(";

    foreach (y, x; (RepresentationTypeTuple!T)[0..len])
    {
        result ~= x.stringof ~ " " ~ fields[y] ~ ", ";
    }

    result = result[0.. $-2] ~ ") { ";

    foreach (x; 0 .. len)
    {
        result ~= "this." ~ fields[x] ~ " = " ~ fields[x] ~ "; ";
    }

    result ~= fun ~ "();";
    result ~= "}";

    return result;
}

struct Foo
{
    int a;
    int b;
    int c;
    int d;

    mixin( FieldInit!(typeof(this), 4, "_this") );

    int sum;
    int average;

    void _this()
    {
        sum = a + b + c + d;
        average = (a + b + c + d) / 4;
    }
}

void main()
{
    auto foo = Foo(1, 2, 3, 4);

    assert(foo.sum == 10);
    assert(foo.average == 2);
}

Mostly.. Of course it doesn't work too good if the fields are placed
below some functions.


More information about the Digitalmars-d mailing list