d可变数据创建不变构.

mixin template Replaceable() {
        // returns a replaced thing when you use it as `with_someField`
        typeof(this) opDispatch(string s, T)(T replacement) if(s.length > 5 && s[0 .. 5] == "with_")
        {
                static foreach(idx, member; typeof(this).tupleof) {
                        static if(__traits(identifier, member) == s[5 .. $])
                                enum argIndex = idx;
                }
                // if the arg is not found you will get an ugly error message here about undefined
                // argIndex.... meh.
                return typeof(this)(this.tupleof[0 .. argIndex], replacement, this.tupleof[argIndex + 1 .. $]);
        }
}

immutable struct Node {
        string label;
        Node* parentNode;
        int port;

        mixin Replaceable; // add the ugly generic code from the top
}

void main() {
        Node i = Node("one", null, 4);
        Node i2 = i.with_port(6); // and now use it like this
        assert(i2.label == "one");
        assert(i2.port == 6);
}

posted @ 2021-11-20 09:09  zjh6  阅读(11)  评论(0)    收藏  举报  来源