Cached property (translate Python -> D)
Victor Porton
porton at narod.ru
Tue Jan 29 17:13:16 UTC 2019
I've successfully implemented it myself:
---
import std.stdio;
mixin template Cached(string name, string baseName = '_' ~ name) {
mixin("private typeof(" ~ baseName ~ ") " ~ name ~ "Cache;");
mixin("private bool " ~ name ~ "IsCached = false;");
mixin("@property typeof(" ~ baseName ~ ") " ~ name ~ "() {\n"
~
"if (" ~ name ~ "IsCached" ~ ") return " ~ name ~
"Cache;\n" ~
name ~ "IsCached = true;\n" ~
"return " ~ name ~ "Cache = " ~ baseName ~ ";\n" ~
'}');
}
struct C {
@property int _f() { writeln("Got!"); return 2; }
mixin Cached!"f";
}
void main(string[] args)
{
C x;
writeln(x.f);
writeln(x.f);
}
---
I think, we should add this to the standard library. What do you
think?
More information about the Digitalmars-d
mailing list