How to use std.functional.memoize inside a class?

I cannot figure out how to use the memoize function inside the class.

import std.functional; class A { int slowFunc(int a, int b) { return 0; } alias memoize!slowFunc fastFunc; } void main() { auto a = new A; a.fastFunc(1,2); } 

This gives an error when trying to compile: Error: 'this' is required to access the slowFunc member

How do I do this job?

+6
source share
1 answer

It does not support yet. We could request a raise. Here is my experimental implementation:

 import std.stdio; import std.traits; import std.typecons; import std.datetime; template isClassStruct(alias fun) { enum bool isClassStruct = (is(fun == class) || is(fun == struct)); } mixin template memoize(alias fun, uint maxSize = uint.max) if (isClassStruct!(__traits(parent, fun))) { ReturnType!fun opCall(ParameterTypeTuple!fun args) { static ReturnType!fun[Tuple!(typeof(args))] memo; auto t = tuple(args); auto p = t in memo; if (p) return *p; static if (maxSize != uint.max) { if (memo.length >= maxSize) memo = null; } mixin("auto r = this." ~ __traits(identifier, fun) ~ "(args);"); memo[t] = r; return r; } } class A { int slowFunc(int a, int b) { int result; foreach (_; 0 .. 1024) { result += a; result += b; } return result; } mixin memoize!slowFunc fastFunc; } enum CallCount = 2048; void main() { A a = new A; auto sw1 = StopWatch(AutoStart.yes); foreach (x; 0 .. CallCount) { a.slowFunc(100, 100); // 11232 usecs } sw1.stop(); writeln(sw1.peek.usecs); auto sw2 = StopWatch(AutoStart.yes); foreach (x; 0 .. CallCount) { a.fastFunc(100, 100); // 302 usecs } sw2.stop(); writeln(sw2.peek.usecs); } 

Time comments for my car, of course. :)

+6
source

Source: https://habr.com/ru/post/926685/


All Articles