lazy variables
aliak
something at something.com
Thu Oct 18 14:03:21 UTC 2018
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.
More information about the Digitalmars-d-learn
mailing list