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:
As an example let's say I have a type 'Window' that represents a win32 window. I'd like to be able to construct an instance of the type with some optional parameters that default to some reasonable settings and create the underlying win32 window.

[...]

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

Reply via email to