Constructors (starstruck noob from C++)

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Jan 20 19:43:34 PST 2011


Be afraid.. be very afraid!

import std.algorithm;
import std.stdio;
import std.conv;

enum fields = [__traits(allMembers, Foo)];

string populateFields(string[] haystack)
{
    string result;
    while (haystack.length > 0)
    {
        switch (haystack[0])
        {
            case "__ctor":
            case "__dtor":
                haystack = haystack[1 .. $];  // skip ctors, dtors,
can't assign those..
                continue;
            default:
        }

        result ~= "this."
               ~ haystack[0]
               ~ " = foo."
               ~ haystack[0]
               ~ ";";

        haystack = haystack[1 .. $];
    }
    return result;
}

class Foo
{
    int x;
    int y;
    this(Foo foo)
    {
        mixin(populateFields(fields));
    }

    this()
    {
    }

    ~this()
    {
    }
}

void main()
{
    auto foo = new Foo();
    foo.x = 1;
    foo.y = 2;

    auto bar = new Foo(foo);

    assert(foo !is bar);
    assert(bar.x == 1);
    assert(bar.y == 2);
}

There's a ton of nonsensical compile errors if I try to use
"[__traits(allMembers, Foo)]" inside the mixin call itself btw.

Okay, this really is just a silly example, but I like having fun with
string mixins. :-)


More information about the Digitalmars-d mailing list