On Monday, 21 January 2019 at 07:57:58 UTC, Simen Kjærås wrote:
On Saturday, 19 January 2019 at 14:26:31 UTC, Zenw wrote:
On Tuesday, 15 January 2019 at 11:14:54 UTC, John Burton wrote:
[...]

how about this

auto With(string code,T)(T value)
{
    with(value)
    {
        mixin(code ~";");
    }
    return value;
}

auto window = Window().With!q{title = "My window",width = 800,fullscreen = true};

The problem with using string mixins like that is when you want to use some local variable:

int width = getWidth();
auto window = Window().With!q{width = width};

This would work:

struct Window {
    string title;
    int width;
    bool fullscreen;
}

auto With(T, Args...)(T ctx, Args args) {
    static foreach (i; 0..Args.length) {
        mixin("ctx."~Args[i].name~" = args[i].value;");
    }
    return ctx;
}

struct args {
    static opDispatch(string _name, T)(T value) {
        struct Result {
            enum name = _name;
            T value;
        }
        return Result(value);
    }
}

unittest {
auto window = Window().With(args.title = "My window", args.width = 800, args.fullscreen = true);
    assert(window.title == "My window");
    assert(window.width == 800);
    assert(window.fullscreen == true);
}

However, I don't see that there's all that much gain compared to just assigning the fields the normal way.

--
  Simen

Thanks everyone for your advice on this.
I'm decided to just use a parameter structure to pass in. Works well and everyone can understand it. The question was really just does D offer a nicer way and the answer appears to be "not really". But the original approach isn't bad anyway.

Reply via email to