d默认类构造器

原文

enum defaultClassConstructor = q{
    this(typeof(this.tupleof) params)
    {
        static foreach(i;0..this.tupleof.length)
        {
            this.tupleof[i] = params[i];
        }
    }
};

struct Color {}

class Point
{
    Color rgba;
    int x, y;
    bool hidden;

    mixin(defaultClassConstructor);
}

void main()
{
    Point p = new Point(Color(),123,456,false);
    assert(p.x == 123);
    assert(p.y == 456);
    assert(p.hidden == false);
}

如下也可以:

this(typeof(this.tupleof) params)
{
    this.tupleof = params; /* 工作 */
}
posted @ 2022-06-17 08:54  zjh6  阅读(16)  评论(0)    收藏  举报  来源