On Wednesday, 17 October 2018 at 20:32:40 UTC, Ali Çehreli wrote:
On 10/17/2018 12:32 AM, aliak wrote:
[...]

Not very clean but something like this:

import std.stdio;

struct LazyVar(alias exp) {
    alias T = typeof(exp());
    T value() {
        static bool initialized = false;
        static T val;

        if (!initialized) {
            val = exp();
            initialized = true;
        }
        return val;
    }

    alias value this;
}

LazyVar!(() {
    writeln("Doing heavy stuff");
    return 42;
}) a;

void main() {
    auto b = a.value;    // Must specify .value or
    int c = a;           // must specify type of value (int).
// Otherwise, b and c have type LazyVar!(...)

    // Some more usage
    b = c = a;

    assert(b == 42);
    assert(c == 42);
}

Ali

Well I guess that's certainly a way to go about it :) Not very clean indeed though.

Reply via email to