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 @   zjh6  阅读(7)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示