www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Can I use memoize with a non-static struct method?

reply Marc <jckj33 gmail.com> writes:
something like this:

 struct S {
   // variables...
   string doGen(int n) { return ""; }
   alias gen = memoize!doGen;
 }
The error I got is:
 Error: need 'this' for 'doGen' of type 'string(int n)'
I can't make doGen static because it access non-static struct members... can I workaround this?
Dec 25 2017
parent Mengu <mengukagan gmail.com> writes:
On Tuesday, 26 December 2017 at 00:47:14 UTC, Marc wrote:
 something like this:

 struct S {
   // variables...
   string doGen(int n) { return ""; }
   alias gen = memoize!doGen;
 }
The error I got is:
 Error: need 'this' for 'doGen' of type 'string(int n)'
I can't make doGen static because it access non-static struct members... can I workaround this?
i don't want to mislead you and i don't know if this is somehow possible but what about some ufcs magic? string doGen(S s, int n) { return "hello ".repeat().take(n).join(); } struct S { int x; auto gen() property { return memoize!doGen(this, x); } } void main() { S s = S(5); s.gen.writeln; s.x = 10; s.gen.writeln; s.x = 15; s.gen.writeln; s.x = 20; s.gen.writeln; }
Dec 26 2017